package router

import (
    "bindbox-game/internal/alert"
    activityapi "bindbox-game/internal/api/activity"
    "bindbox-game/internal/api/admin"
    commonapi "bindbox-game/internal/api/common"
    appapi "bindbox-game/internal/api/app"
    guildapi "bindbox-game/internal/api/guild"
    userapi "bindbox-game/internal/api/user"
    "bindbox-game/internal/dblogger"
    "bindbox-game/internal/pkg/core"
    "bindbox-game/internal/pkg/logger"
	"bindbox-game/internal/pkg/startup"
	"bindbox-game/internal/repository/mysql"
	"bindbox-game/internal/router/interceptor"

	"github.com/pkg/errors"
)

func NewHTTPMux(logger logger.CustomLogger, db mysql.Repo) (core.Mux, error) {
	if logger == nil {
		return nil, errors.New("logger required")
	}

	if db == nil {
		return nil, errors.New("db required")
	}

	mux, err := core.New(logger,
		core.WithEnableCors(),
		core.WithEnableSwagger(),
		core.WithEnablePProf(),
		core.WithAlertNotify(alert.NotifyHandler()),
		core.WithRequestLogger(dblogger.LoggerHandler(db)),
	)

	if err != nil {
		panic(err)
	}

	// 实例化拦截器
	adminHandler := admin.New(logger, db)
	activityHandler := activityapi.New(logger, db)
	guildHandler := guildapi.New(logger, db)
	userHandler := userapi.New(logger, db)
	commonHandler := commonapi.New(logger, db)
	intc := interceptor.New(logger, db)

	// 管理端非认证接口路由组
	adminNonAuthApiRouter := mux.Group("/api/admin")
	{
		adminNonAuthApiRouter.GET("/license/status", func(ctx core.Context) {
			ctx.Payload(startup.Info())
		})

		adminNonAuthApiRouter.POST("/login", adminHandler.Login()) // 登录
	}

	// 管理端认证接口路由组
	adminAuthApiRouter := mux.Group("/api/admin", core.WrapAuthHandler(intc.AdminTokenAuthVerify))

	// 系统管理接口（为前端模板路径兼容，挂载到 /api）
	systemApiRouter := mux.Group("/api", core.WrapAuthHandler(intc.AdminTokenAuthVerify))
	{
		adminAuthApiRouter.POST("/create", adminHandler.CreateAdmin())
		adminAuthApiRouter.PUT("/:id", adminHandler.ModifyAdmin())
		adminAuthApiRouter.POST("/delete", adminHandler.DeleteAdmin())
		adminAuthApiRouter.GET("/list", adminHandler.PageList())

		adminAuthApiRouter.GET("/activity_categories", adminHandler.ListActivityCategories())
		adminAuthApiRouter.POST("/activities", adminHandler.CreateActivity())
		adminAuthApiRouter.PUT("/activities/:activity_id", adminHandler.ModifyActivity())
		adminAuthApiRouter.DELETE("/activities/:activity_id", adminHandler.DeleteActivity())
		adminAuthApiRouter.GET("/activities/:activity_id", adminHandler.GetActivityDetail())
		adminAuthApiRouter.GET("/activities/:activity_id/issues", adminHandler.ListActivityIssues())
		adminAuthApiRouter.POST("/activities/:activity_id/issues", adminHandler.CreateActivityIssue())
		adminAuthApiRouter.PUT("/activities/:activity_id/issues/:issue_id", adminHandler.ModifyActivityIssue())
		adminAuthApiRouter.DELETE("/activities/:activity_id/issues/:issue_id", adminHandler.DeleteActivityIssue())
		adminAuthApiRouter.POST("/activities/:activity_id/issues/:issue_id/rewards", adminHandler.CreateIssueRewards())
		adminAuthApiRouter.GET("/activities/:activity_id/issues/:issue_id/rewards", adminHandler.ListIssueRewards())
		adminAuthApiRouter.PUT("/activities/:activity_id/issues/:issue_id/rewards/:reward_id", adminHandler.ModifyIssueReward())
		adminAuthApiRouter.DELETE("/activities/:activity_id/issues/:issue_id/rewards/:reward_id", adminHandler.DeleteIssueReward())

		adminAuthApiRouter.POST("/guilds", adminHandler.CreateGuild())
		adminAuthApiRouter.PUT("/guilds/:guild_id", adminHandler.ModifyGuild())
		adminAuthApiRouter.DELETE("/guilds/:guild_id", adminHandler.DeleteGuild())
		adminAuthApiRouter.GET("/guilds/:guild_id", adminHandler.GetGuildDetail())
		adminAuthApiRouter.GET("/guilds/:guild_id/members", adminHandler.ListGuildMembers())

		// 商品管理：分类与商品
		adminAuthApiRouter.POST("/product_categories", adminHandler.CreateProductCategory())
		adminAuthApiRouter.PUT("/product_categories/:category_id", adminHandler.ModifyProductCategory())
		adminAuthApiRouter.DELETE("/product_categories/:category_id", adminHandler.DeleteProductCategory())
		adminAuthApiRouter.GET("/product_categories", adminHandler.ListProductCategories())
		adminAuthApiRouter.POST("/products", adminHandler.CreateProduct())
		adminAuthApiRouter.PUT("/products/:product_id", adminHandler.ModifyProduct())
		adminAuthApiRouter.DELETE("/products/:product_id", adminHandler.DeleteProduct())
		adminAuthApiRouter.GET("/products", adminHandler.ListProducts())

		// 轮播图管理
		adminAuthApiRouter.POST("/banners", adminHandler.CreateBanner())
		adminAuthApiRouter.PUT("/banners/:banner_id", adminHandler.ModifyBanner())
		adminAuthApiRouter.DELETE("/banners/:banner_id", adminHandler.DeleteBanner())
		adminAuthApiRouter.GET("/banners", adminHandler.ListBanners())

		// 用户管理
		adminAuthApiRouter.GET("/users", adminHandler.ListAppUsers())
		adminAuthApiRouter.GET("/users/:user_id/invites", adminHandler.ListUserInvites())
		adminAuthApiRouter.GET("/users/:user_id/orders", adminHandler.ListUserOrders())
		adminAuthApiRouter.GET("/users/:user_id/coupons", adminHandler.ListUserCoupons())
		adminAuthApiRouter.GET("/users/:user_id/points", adminHandler.ListUserPoints())
		adminAuthApiRouter.GET("/users/:user_id/points/balance", adminHandler.GetUserPointsBalance())
		adminAuthApiRouter.POST("/users/:user_id/points/add", adminHandler.AddUserPoints())
		adminAuthApiRouter.POST("/users/:user_id/coupons/add", adminHandler.AddUserCoupon())
		adminAuthApiRouter.POST("/users/:user_id/rewards/grant", adminHandler.GrantReward())
		adminAuthApiRouter.GET("/users/:user_id/inventory", adminHandler.ListUserInventory())
		adminAuthApiRouter.GET("/users/:user_id/item_cards", adminHandler.ListUserItemCards())

		// 道具卡管理
		adminAuthApiRouter.POST("/system_item_cards", adminHandler.CreateSystemItemCard())
		adminAuthApiRouter.PUT("/system_item_cards/:item_card_id", adminHandler.ModifySystemItemCard())
		adminAuthApiRouter.DELETE("/system_item_cards/:item_card_id", adminHandler.DeleteSystemItemCard())
		adminAuthApiRouter.GET("/system_item_cards", adminHandler.ListSystemItemCards())
		// 优惠券管理
		adminAuthApiRouter.POST("/system_coupons", adminHandler.CreateSystemCoupon())
		adminAuthApiRouter.PUT("/system_coupons/:coupon_id", adminHandler.ModifySystemCoupon())
		adminAuthApiRouter.DELETE("/system_coupons/:coupon_id", adminHandler.DeleteSystemCoupon())
		adminAuthApiRouter.GET("/system_coupons", adminHandler.ListSystemCoupons())
		adminAuthApiRouter.POST("/users/:user_id/item_cards", adminHandler.AssignUserItemCard())
		// 通用上传
		systemApiRouter.POST("/common/upload/wangeditor", commonHandler.UploadWangEditorImage())
	}

	// 系统管理：用户/角色/菜单
	{
		systemApiRouter.GET("/user/list", adminHandler.ListUsers())
		systemApiRouter.GET("/role/list", adminHandler.ListRoles())
		systemApiRouter.GET("/v3/system/menus/simple", adminHandler.ListSimpleMenus())
		systemApiRouter.POST("/role", adminHandler.CreateRole())
		systemApiRouter.PUT("/role/:role_id", adminHandler.ModifyRole())
		systemApiRouter.DELETE("/role/:role_id", adminHandler.DeleteRole())
		systemApiRouter.POST("/role/:role_id/users", adminHandler.AssignRoleUsers())
		systemApiRouter.GET("/role/:role_id/users", adminHandler.ListRoleUsers())
		systemApiRouter.DELETE("/role/:role_id/users/:admin_id", adminHandler.RemoveRoleUser())
		systemApiRouter.POST("/menu", adminHandler.CreateMenu())
		systemApiRouter.PUT("/menu/:menu_id", adminHandler.ModifyMenu())
		systemApiRouter.DELETE("/menu/:menu_id", adminHandler.DeleteMenu())
		systemApiRouter.GET("/menu/:menu_id/actions", adminHandler.ListMenuActions())
		systemApiRouter.POST("/menu/:menu_id/actions", adminHandler.CreateMenuActions())
		systemApiRouter.DELETE("/menu/:menu_id/actions/:action_id", adminHandler.DeleteMenuAction())
		systemApiRouter.POST("/role/:role_id/menus", adminHandler.AssignRoleMenus())
		systemApiRouter.POST("/role/:role_id/actions", adminHandler.AssignRoleActions())
	}

    // APP 端公开接口路由组
    appPublicApiRouter := mux.Group("/api/app")
    {
        appPublicApiRouter.GET("/activities", activityHandler.ListActivities())
        appPublicApiRouter.GET("/activities/:activity_id", activityHandler.GetActivityDetail())
        appPublicApiRouter.GET("/activities/:activity_id/issues", activityHandler.ListActivityIssues())
        appPublicApiRouter.GET("/activities/:activity_id/issues/:issue_id/rewards", activityHandler.ListIssueRewards())
        appPublicApiRouter.GET("/activities/:activity_id/issues/:issue_id/draw_logs", activityHandler.ListDrawLogs())

        appPublicApiRouter.GET("/guilds", guildHandler.ListGuilds())
        appPublicApiRouter.GET("/guilds/:guild_id", guildHandler.GetGuildDetail())
        appPublicApiRouter.POST("/guilds/:guild_id/members", guildHandler.JoinGuild())
        appPublicApiRouter.DELETE("/guilds/:guild_id/members/:user_id", guildHandler.LeaveGuild())
        appPublicApiRouter.GET("/guilds/:guild_id/members", guildHandler.ListGuildMembers())

        // APP 端轮播图
        appPublicApiRouter.GET("/banners", appapi.NewBanner(logger, db).ListBannersForApp())

        // 登录保持公开
        appPublicApiRouter.POST("/users/weixin/login", userHandler.WeixinLogin())
    }

    // APP 端认证接口路由组
        appAuthApiRouter := mux.Group("/api/app", core.WrapAuthHandler(intc.AppTokenAuthVerify))
        {
            appAuthApiRouter.PUT("/users/:user_id", userHandler.ModifyUser())
            appAuthApiRouter.GET("/users/:user_id/orders", userHandler.ListUserOrders())
            appAuthApiRouter.GET("/users/:user_id/coupons", userHandler.ListUserCoupons())
            appAuthApiRouter.GET("/users/:user_id/points", userHandler.ListUserPoints())
            appAuthApiRouter.GET("/users/:user_id/points/balance", userHandler.GetUserPointsBalance())
            appAuthApiRouter.GET("/users/:user_id/stats", userHandler.GetUserStats())
            appAuthApiRouter.POST("/users/:user_id/phone/bind", userHandler.BindPhone())
            appAuthApiRouter.GET("/users/:user_id/invites", userHandler.ListUserInvites())
            appAuthApiRouter.GET("/users/:user_id/item_cards", userHandler.ListUserItemCards())
            appAuthApiRouter.GET("/users/:user_id/item_cards/uses", userHandler.ListUserItemCardUses())
            appAuthApiRouter.POST("/users/:user_id/addresses", userHandler.AddUserAddress())
            appAuthApiRouter.GET("/users/:user_id/addresses", userHandler.ListUserAddresses())
            appAuthApiRouter.PUT("/users/:user_id/addresses/:address_id/default", userHandler.SetDefaultUserAddress())
            appAuthApiRouter.DELETE("/users/:user_id/addresses/:address_id", userHandler.DeleteUserAddress())
        }

	return mux, nil
}
