package agent

import (
	"context"
	"database/sql"
	"encoding/hex"
	"fmt"
	"qnc-server/app/main/model"
	"qnc-server/common/ctxdata"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"time"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"qnc-server/app/main/api/internal/service"
	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameAuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRealNameAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameAuthLogic {
	return &RealNameAuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RealNameAuthLogic) RealNameAuth(req *types.RealNameAuthReq) (resp *types.RealNameAuthResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	// 1. 获取代理信息
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			return nil, errors.Wrapf(xerr.NewErrMsg("您不是代理"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 2. 验证手机号是否匹配
	agentMobile, err := crypto.DecryptMobile(agent.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密手机号失败, %v", err)
	}
	if agentMobile != req.Mobile {
		return nil, errors.Wrapf(xerr.NewErrMsg("手机号与代理注册手机号不匹配"), "")
	}

	// 3. 验证验证码
	encryptedMobile, err := crypto.EncryptMobile(req.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败, %v", err)
	}
	redisKey := fmt.Sprintf("realName:%s", encryptedMobile)
	cacheCode, err := l.svcCtx.Redis.Get(redisKey)
	if err != nil {
		if errors.Is(err, redis.Nil) {
			return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "读取验证码失败, %v", err)
	}
	if cacheCode != req.Code {
		return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "")
	}

	// 4. 三要素核验（姓名、身份证号、手机号）
	verification, err := l.svcCtx.VerificationService.ThreeFactorVerification(service.ThreeFactorVerificationRequest{
		Name:   req.Name,
		IDCard: req.IdCard,
		Mobile: req.Mobile,
	})
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "三要素核验失败: %v", err)
	}
	if !verification.Passed {
		if verification.Err != nil {
			return nil, errors.Wrapf(xerr.NewErrMsg(verification.Err.Error()), "三要素核验不通过")
		}
		return nil, errors.Wrapf(xerr.NewErrMsg("三要素核验不通过"), "")
	}

	// 5. 检查是否已有实名认证记录
	existingRealName, err := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agent.Id)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询实名认证记录失败, %v", err)
	}

	// 6. 使用事务处理实名认证（三要素核验通过后直接设置为已通过）
	err = l.svcCtx.AgentRealNameModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
		// 加密身份证号和手机号
		key, err := hex.DecodeString(l.svcCtx.Config.Encrypt.SecretKey)
		if err != nil {
			return errors.Wrapf(err, "解析密钥失败")
		}
		encryptedIdCard, err := crypto.EncryptIDCard(req.IdCard, key)
		if err != nil {
			return errors.Wrapf(err, "加密身份证号失败")
		}

		encryptedMobile, err := crypto.EncryptMobile(req.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
		if err != nil {
			return errors.Wrapf(err, "加密手机号失败")
		}

		verifyTime := time.Now()
		if existingRealName != nil {
			// 更新现有记录
			existingRealName.Name = req.Name
			existingRealName.IdCard = encryptedIdCard
			existingRealName.Mobile = encryptedMobile
			existingRealName.VerifyTime = sql.NullTime{Time: verifyTime, Valid: true} // 三要素核验通过，设置验证时间
			if err := l.svcCtx.AgentRealNameModel.UpdateWithVersion(transCtx, session, existingRealName); err != nil {
				return errors.Wrapf(err, "更新实名认证记录失败")
			}
		} else {
			// 创建新记录
			realName := &model.AgentRealName{
				AgentId:    agent.Id,
				Name:       req.Name,
				IdCard:     encryptedIdCard,
				Mobile:     encryptedMobile,
				VerifyTime: sql.NullTime{Time: verifyTime, Valid: true}, // 三要素核验通过，设置验证时间
			}
			if _, err := l.svcCtx.AgentRealNameModel.Insert(transCtx, session, realName); err != nil {
				return errors.Wrapf(err, "创建实名认证记录失败")
			}
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.RealNameAuthResp{
		Status: model.AgentRealNameStatusApproved, // 三要素核验通过，直接返回已通过
	}, nil
}
