package pub

import (
	"errors"

	"bsm/full/module/base/mgt/internal/impl"
	"bsm/full/module/base/mgt/internal/libs"
	"bsm/full/module/base/mgt/internal/models"
	"bsm/full/module/base/mgt/internal/types"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/infra"
	"git.apinb.com/bsm-sdk/core/printer"
	coreutils "git.apinb.com/bsm-sdk/core/utils"
	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// ForgetPwdBySms 忘记密码-通过短信更改
func ForgetPwdBySms(c *gin.Context) {
	request := types.ForgetPwdRequest{}

	if err := c.ShouldBindJSON(&request); err != nil {
		infra.Response.Error(c, errcode.ErrJsonUnmarshal)
		return
	}

	if err := libs.ValidateStruct(&request); err != nil {
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if request.Code == "" {
		printer.Error("验证码不能为空")
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	var data models.MgtUser
	if err := models.DBService.Model(&models.MgtUser{}).Where("account = ?", request.Account).First(&data).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			infra.Response.Error(c, errcode.ErrRecordNotFound)
			return
		}
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	if data.Phone != request.Phone {
		printer.Error("账号与手机号不匹配: account=%s, phone=%s", request.Account, request.Phone)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	smsKey := types.KeyPrefix + request.Phone
	storedCode, err := impl.RedisService.Client.Get(impl.RedisService.Ctx, smsKey).Result()
	if err != nil {
		if errors.Is(err, redis.Nil) {
			printer.Error("验证码已过期或不存在: phone=%s", request.Phone)
			infra.Response.Error(c, errcode.ErrInvalidArgument)
			return
		}
		printer.Error("读取验证码异常: %v", err)
		infra.Response.Error(c, errcode.ErrInternal)
		return
	}
	if storedCode != request.Code {
		printer.Error("验证码不正确: phone=%s", request.Phone)
		infra.Response.Error(c, errcode.ErrInvalidArgument)
		return
	}

	if data.Salt == "" {
		data.Salt = coreutils.UUID()
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(request.Password+data.Salt), bcrypt.DefaultCost)
	if err != nil {
		printer.Error("密码加密异常: %v", err)
		infra.Response.Error(c, errcode.ErrInternal)
		return
	}

	if err := models.DBService.Model(&models.MgtUser{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"password": string(hashedPassword),
		"salt":     data.Salt,
	}).Error; err != nil {
		infra.Response.Error(c, errcode.ErrDB)
		return
	}

	if err := impl.RedisService.Client.Del(impl.RedisService.Ctx, smsKey).Err(); err != nil {
		printer.Error("清除验证码缓存异常: %v", err)
	}

	printer.Info("密码重置成功: account=%s, phone=%s", request.Account, request.Phone)
	infra.Response.Success(c, "密码重置成功")
}

// ForgetPwdByPwd 忘记密码-通过旧密码更改
func ForgetPwdByPwd(c *gin.Context) {
}
