package router

import (
	"fmt"

	"hyapp-admin-server/internal/config"
	"hyapp-admin-server/internal/middleware"
	"hyapp-admin-server/internal/modules/achievementconfig"
	"hyapp-admin-server/internal/modules/activitytemplate"
	"hyapp-admin-server/internal/modules/adminuser"
	"hyapp-admin-server/internal/modules/agencyopening"
	"hyapp-admin-server/internal/modules/appconfig"
	"hyapp-admin-server/internal/modules/appregistry"
	"hyapp-admin-server/internal/modules/appuser"
	"hyapp-admin-server/internal/modules/audit"
	authroutes "hyapp-admin-server/internal/modules/auth"
	"hyapp-admin-server/internal/modules/coinledger"
	"hyapp-admin-server/internal/modules/countryregion"
	"hyapp-admin-server/internal/modules/cprelation"
	"hyapp-admin-server/internal/modules/cpweeklyrank"
	"hyapp-admin-server/internal/modules/cumulativerechargereward"
	"hyapp-admin-server/internal/modules/dailytask"
	"hyapp-admin-server/internal/modules/dashboard"
	"hyapp-admin-server/internal/modules/databi"
	"hyapp-admin-server/internal/modules/externaladmin"
	"hyapp-admin-server/internal/modules/financeorder"
	"hyapp-admin-server/internal/modules/financewithdrawal"
	"hyapp-admin-server/internal/modules/firstrechargereward"
	"hyapp-admin-server/internal/modules/fullservernotice"
	gamemanagement "hyapp-admin-server/internal/modules/gamemanagement"
	"hyapp-admin-server/internal/modules/giftdiamond"
	"hyapp-admin-server/internal/modules/giftrecord"
	"hyapp-admin-server/internal/modules/health"
	"hyapp-admin-server/internal/modules/hostagencypolicy"
	"hyapp-admin-server/internal/modules/hostorg"
	"hyapp-admin-server/internal/modules/hostsalarysettlement"
	"hyapp-admin-server/internal/modules/hostwithdrawal"
	"hyapp-admin-server/internal/modules/inviteactivityreward"
	"hyapp-admin-server/internal/modules/job"
	"hyapp-admin-server/internal/modules/levelconfig"
	"hyapp-admin-server/internal/modules/menu"
	"hyapp-admin-server/internal/modules/opscenter"
	"hyapp-admin-server/internal/modules/payment"
	"hyapp-admin-server/internal/modules/pointwithdrawalconfig"
	"hyapp-admin-server/internal/modules/policyconfig"
	"hyapp-admin-server/internal/modules/prettyid"
	"hyapp-admin-server/internal/modules/rbac"
	"hyapp-admin-server/internal/modules/redpacket"
	"hyapp-admin-server/internal/modules/regionblock"
	"hyapp-admin-server/internal/modules/registrationreward"
	reportmodule "hyapp-admin-server/internal/modules/report"
	resourcemodule "hyapp-admin-server/internal/modules/resource"
	"hyapp-admin-server/internal/modules/riskconfig"
	"hyapp-admin-server/internal/modules/roomadmin"
	"hyapp-admin-server/internal/modules/roomrocket"
	"hyapp-admin-server/internal/modules/roomturnoverreward"
	"hyapp-admin-server/internal/modules/search"
	"hyapp-admin-server/internal/modules/sevendaycheckin"
	"hyapp-admin-server/internal/modules/team"
	"hyapp-admin-server/internal/modules/teamsalarypolicy"
	"hyapp-admin-server/internal/modules/teamsalarysettlement"
	"hyapp-admin-server/internal/modules/upload"
	"hyapp-admin-server/internal/modules/userleaderboard"
	"hyapp-admin-server/internal/modules/vipconfig"
	"hyapp-admin-server/internal/modules/weeklystar"
	"hyapp-admin-server/internal/modules/wheel"
	"hyapp-admin-server/internal/platform/logging"
	"hyapp-admin-server/internal/repository"
	"hyapp-admin-server/internal/service"

	"github.com/gin-gonic/gin"
)

type Handlers struct {
	AdminUser             *adminuser.Handler
	AgencyOpening         *agencyopening.Handler
	ActivityTemplate      *activitytemplate.Handler
	AchievementConfig     *achievementconfig.Handler
	AppConfig             *appconfig.Handler
	AppRegistry           *appregistry.Handler
	AppUser               *appuser.Handler
	Audit                 *audit.Handler
	Auth                  *authroutes.Handler
	CoinLedger            *coinledger.Handler
	CountryRegion         *countryregion.Handler
	CPRelation            *cprelation.Handler
	CPWeeklyRank          *cpweeklyrank.Handler
	CumulativeRecharge    *cumulativerechargereward.Handler
	DailyTask             *dailytask.Handler
	Dashboard             *dashboard.Handler
	Databi                *databi.Handler
	FirstRechargeReward   *firstrechargereward.Handler
	FinanceOrder          *financeorder.Handler
	FinanceWithdrawal     *financewithdrawal.Handler
	ExternalAdmin         *externaladmin.Handler
	FullServerNotice      *fullservernotice.Handler
	Game                  *gamemanagement.Handler
	GiftDiamond           *giftdiamond.Handler
	GiftRecord            *giftrecord.Handler
	Health                *health.Handler
	HostAgencyPolicy      *hostagencypolicy.Handler
	HostOrg               *hostorg.Handler
	HostSalarySettlement  *hostsalarysettlement.Handler
	HostWithdrawal        *hostwithdrawal.Handler
	InviteActivityReward  *inviteactivityreward.Handler
	Job                   *job.Handler
	LevelConfig           *levelconfig.Handler
	Menu                  *menu.Handler
	OpsCenter             *opscenter.Handler
	Payment               *payment.Handler
	PolicyConfig          *policyconfig.Handler
	PointWithdrawalConfig *pointwithdrawalconfig.Handler
	PrettyID              *prettyid.Handler
	RBAC                  *rbac.Handler
	RedPacket             *redpacket.Handler
	Report                *reportmodule.Handler
	RegistrationReward    *registrationreward.Handler
	RegionBlock           *regionblock.Handler
	Resource              *resourcemodule.Handler
	RiskConfig            *riskconfig.Handler
	RoomAdmin             *roomadmin.Handler
	RoomRocket            *roomrocket.Handler
	RoomTurnoverReward    *roomturnoverreward.Handler
	Search                *search.Handler
	SevenDayCheckIn       *sevendaycheckin.Handler
	Team                  *team.Handler
	TeamSalaryPolicy      *teamsalarypolicy.Handler
	TeamSalarySettlement  *teamsalarysettlement.Handler
	Upload                *upload.Handler
	UserLeaderboard       *userleaderboard.Handler
	VIPConfig             *vipconfig.Handler
	WeeklyStar            *weeklystar.Handler
	Wheel                 *wheel.Handler
}

func New(cfg config.Config, auth *service.AuthService, store *repository.Store, h Handlers) *gin.Engine {
	engine := gin.New()
	// SetTrustedProxies must be called even for an empty list; otherwise Gin 1.10
	// trusts every proxy by default and client-controlled XFF can defeat IP limits.
	// Config validation rejects malformed entries before startup; panic here catches
	// only tests/manual constructors that bypass the normal validated load path.
	if err := engine.SetTrustedProxies(cfg.TrustedProxies); err != nil {
		panic(fmt.Sprintf("configure trusted proxies: %v", err))
	}
	engine.Use(middleware.RequestID(), middleware.AppCode(), logging.GinAccessLogger(), gin.Recovery(), middleware.CORS(cfg))

	engine.GET("/healthz", h.Health.Health)
	engine.GET("/readyz", h.Health.Ready)

	api := engine.Group("/api/v1")
	protected := api.Group("")
	protected.Use(middleware.AuthRequired(auth, store), middleware.Audit(h.Audit))
	appProtected := protected.Group("")
	appProtected.Use(middleware.RequireAppScope(store))

	authroutes.RegisterRoutes(api, protected, h.Auth)
	financewithdrawal.RegisterIntegrationRoutes(api, h.FinanceWithdrawal)
	externaladmin.RegisterExternalRoutes(api, h.ExternalAdmin, externaladmin.BusinessHandlers{
		AppUser: h.AppUser, HostOrg: h.HostOrg, RoomAdmin: h.RoomAdmin, Resource: h.Resource,
		PrettyID: h.PrettyID, AppConfig: h.AppConfig, VIPConfig: h.VIPConfig, Upload: h.Upload,
	})
	agencyopening.RegisterRoutes(appProtected, h.AgencyOpening)
	activitytemplate.RegisterRoutes(appProtected, h.ActivityTemplate)
	achievementconfig.RegisterRoutes(appProtected, h.AchievementConfig)
	coinledger.RegisterRoutes(appProtected, h.CoinLedger)
	menu.RegisterRoutes(protected, h.Menu)
	rbac.RegisterRoutes(protected, h.RBAC)
	redpacket.RegisterRoutes(appProtected, h.RedPacket)
	reportmodule.RegisterRoutes(appProtected, h.Report)
	resourcemodule.RegisterRoutes(appProtected, h.Resource)
	adminuser.RegisterRoutes(protected, h.AdminUser)
	externaladmin.RegisterAdminRoutes(appProtected, h.ExternalAdmin)
	appuser.RegisterRoutes(appProtected, h.AppUser)
	appregistry.RegisterRoutes(protected, h.AppRegistry)
	appconfig.RegisterRoutes(appProtected, h.AppConfig)
	countryregion.RegisterRoutes(appProtected, h.CountryRegion)
	cprelation.RegisterRoutes(appProtected, h.CPRelation)
	cpweeklyrank.RegisterRoutes(appProtected, h.CPWeeklyRank)
	cumulativerechargereward.RegisterRoutes(appProtected, h.CumulativeRecharge)
	dailytask.RegisterRoutes(appProtected, h.DailyTask)
	firstrechargereward.RegisterRoutes(appProtected, h.FirstRechargeReward)
	financeorder.RegisterRoutes(protected, h.FinanceOrder)
	financewithdrawal.RegisterRoutes(protected, h.FinanceWithdrawal)
	fullservernotice.RegisterRoutes(appProtected, h.FullServerNotice)
	registrationreward.RegisterRoutes(appProtected, h.RegistrationReward)
	regionblock.RegisterRoutes(appProtected, h.RegionBlock)
	riskconfig.RegisterRoutes(appProtected, h.RiskConfig)
	gamemanagement.RegisterRoutes(appProtected, h.Game)
	giftdiamond.RegisterRoutes(appProtected, h.GiftDiamond)
	giftrecord.RegisterRoutes(appProtected, h.GiftRecord)
	roomadmin.RegisterRoutes(appProtected, h.RoomAdmin)
	roomrocket.RegisterRoutes(appProtected, h.RoomRocket)
	roomturnoverreward.RegisterRoutes(appProtected, h.RoomTurnoverReward)
	dashboard.RegisterRoutes(appProtected, protected, h.Dashboard)
	databi.RegisterRoutes(protected, h.Databi)
	hostagencypolicy.RegisterRoutes(appProtected, h.HostAgencyPolicy)
	hostsalarysettlement.RegisterRoutes(appProtected, h.HostSalarySettlement)
	hostorg.RegisterRoutes(appProtected, h.HostOrg)
	hostwithdrawal.RegisterRoutes(appProtected, h.HostWithdrawal)
	inviteactivityreward.RegisterRoutes(appProtected, h.InviteActivityReward)
	audit.RegisterRoutes(protected, h.Audit)
	payment.RegisterRoutes(protected, appProtected, h.Payment)
	policyconfig.RegisterRoutes(appProtected, h.PolicyConfig)
	pointwithdrawalconfig.RegisterRoutes(appProtected, h.PointWithdrawalConfig)
	prettyid.RegisterRoutes(appProtected, h.PrettyID)
	job.RegisterRoutes(protected, h.Job)
	levelconfig.RegisterRoutes(appProtected, h.LevelConfig)
	// Ops Center 是跨 App 工作台：它必须先读取应用目录，再按 app_code 扇出查询。
	// 这里仅沿用登录、审计和模块内 lucky-gift 权限，不能要求尚未选出的 X-App-Code。
	opscenter.RegisterRoutes(protected, h.OpsCenter)
	upload.RegisterRoutes(appProtected, h.Upload)
	search.RegisterRoutes(protected, h.Search)
	sevendaycheckin.RegisterRoutes(appProtected, h.SevenDayCheckIn)
	team.RegisterRoutes(protected, h.Team)
	teamsalarypolicy.RegisterRoutes(appProtected, h.TeamSalaryPolicy)
	teamsalarysettlement.RegisterRoutes(appProtected, h.TeamSalarySettlement)
	userleaderboard.RegisterRoutes(appProtected, h.UserLeaderboard)
	vipconfig.RegisterRoutes(appProtected, h.VIPConfig)
	weeklystar.RegisterRoutes(appProtected, h.WeeklyStar)
	wheel.RegisterRoutes(appProtected, h.Wheel)

	return engine
}
