package auth

import (
	"github.com/gin-gonic/gin"
	commonLogic "github.com/perfect-panel/server/internal/logic/common"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/constant"
	"github.com/perfect-panel/server/pkg/result"
)

// Check legacy verification code
func CheckCodeLegacyHandler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
	return CheckCodeLegacyV1Handler(svcCtx)
}

func CheckCodeLegacyV1Handler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
	return checkCodeLegacyHandler(svcCtx, false)
}

func CheckCodeLegacyV2Handler(svcCtx *svc.ServiceContext) func(c *gin.Context) {
	return checkCodeLegacyHandler(svcCtx, true)
}

func checkCodeLegacyHandler(svcCtx *svc.ServiceContext, consume bool) func(c *gin.Context) {
	return func(c *gin.Context) {
		var req types.LegacyCheckVerificationCodeRequest
		_ = c.ShouldBind(&req)
		validateErr := svcCtx.Validate(&req)
		if validateErr != nil {
			result.ParamErrorResult(c, validateErr)
			return
		}

		normalizedReq, legacyType3Mapped, err := commonLogic.NormalizeLegacyCheckVerificationCodeRequest(&req)
		if err != nil {
			result.ParamErrorResult(c, err)
			return
		}

		l := commonLogic.NewCheckVerificationCodeLogic(c.Request.Context(), svcCtx)
		resp, err := l.CheckVerificationCodeWithBehavior(normalizedReq, commonLogic.VerifyCodeCheckBehavior{
			Source:             "legacy",
			Consume:            consume,
			LegacyType3Mapped:  legacyType3Mapped,
			AllowSceneFallback: constant.ParseVerifyType(normalizedReq.Type) != constant.DeleteAccount,
		})

		legacyResp := &types.LegacyCheckVerificationCodeResponse{}
		if resp != nil {
			legacyResp.Status = resp.Status
			legacyResp.Exist = resp.Status
		}

		result.HttpResult(c, legacyResp, err)
	}
}
