package bootstrap

import (
	"context"
	"time"

	"github.com/break/junhong_cmp_fiber/internal/middleware"
	pkgauth "github.com/break/junhong_cmp_fiber/pkg/auth"
	"github.com/break/junhong_cmp_fiber/pkg/config"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
	"github.com/break/junhong_cmp_fiber/pkg/errors"
	pkgmiddleware "github.com/break/junhong_cmp_fiber/pkg/middleware"
	"github.com/gofiber/fiber/v2"
)

// initMiddlewares 初始化所有中间件
func initMiddlewares(deps *Dependencies, stores *stores) *Middlewares {
	// 获取全局配置
	cfg := config.Get()

	// 创建 JWT Manager
	jwtManager := pkgauth.NewJWTManager(cfg.JWT.SecretKey, cfg.JWT.TokenDuration)

	// 创建个人客户认证中间件
	personalAuthMiddleware := middleware.NewPersonalAuthMiddleware(jwtManager, deps.Redis, deps.Logger)

	// 创建 Token Manager（用于后台和H5认证）
	accessTTL := time.Duration(cfg.JWT.AccessTokenTTL) * time.Second
	refreshTTL := time.Duration(cfg.JWT.RefreshTokenTTL) * time.Second
	tokenManager := pkgauth.NewTokenManager(deps.Redis, accessTTL, refreshTTL)

	// 创建后台认证中间件（传入 ShopStore 以支持预计算下级店铺 ID）
	adminAuthMiddleware := createAdminAuthMiddleware(tokenManager, stores.Shop)

	agentOpenAPIAuthMiddleware := middleware.NewAgentOpenAPIAuthMiddleware(middleware.AgentOpenAPIAuthConfig{
		AccountStore: stores.Account,
		ShopStore:    stores.Shop,
		Redis:        deps.Redis,
	})

	return &Middlewares{
		PersonalAuth:     personalAuthMiddleware,
		AdminAuth:        adminAuthMiddleware,
		AgentOpenAPIAuth: agentOpenAPIAuthMiddleware,
	}
}

func createAdminAuthMiddleware(tokenManager *pkgauth.TokenManager, shopStore pkgmiddleware.AuthShopStoreInterface) fiber.Handler {
	return pkgmiddleware.Auth(pkgmiddleware.AuthConfig{
		TokenValidator: func(token string) (*pkgmiddleware.UserContextInfo, error) {
			tokenInfo, err := tokenManager.ValidateAccessToken(context.Background(), token)
			if err != nil {
				return nil, errors.New(errors.CodeInvalidToken, "认证令牌无效或已过期")
			}

			// 检查用户类型：后台允许 SuperAdmin(1), Platform(2), Agent(3), Enterprise(4)
			if tokenInfo.UserType != constants.UserTypeSuperAdmin &&
				tokenInfo.UserType != constants.UserTypePlatform &&
				tokenInfo.UserType != constants.UserTypeAgent &&
				tokenInfo.UserType != constants.UserTypeEnterprise {
				return nil, errors.New(errors.CodeForbidden, "权限不足")
			}

			return &pkgmiddleware.UserContextInfo{
				UserID:       tokenInfo.UserID,
				UserType:     tokenInfo.UserType,
				Username:     tokenInfo.Username,
				ShopID:       tokenInfo.ShopID,
				EnterpriseID: tokenInfo.EnterpriseID,
			}, nil
		},
		SkipPaths: []string{"/api/admin/login", "/api/admin/refresh-token"},
		ShopStore: shopStore,
	})
}
