package admin_agent

import (
    "context"
    "database/sql"
    "time"
    "qnc-server/app/main/model"
    "qnc-server/common/tool"
    "qnc-server/common/xerr"

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

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

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

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

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

func (l *AdminGenerateDiamondInviteCodeLogic) AdminGenerateDiamondInviteCode(req *types.AdminGenerateDiamondInviteCodeReq) (resp *types.AdminGenerateDiamondInviteCodeResp, err error) {
	// 1. 验证生成数量
	if req.Count <= 0 || req.Count > 100 {
		return nil, errors.Wrapf(xerr.NewErrMsg("生成数量必须在1-100之间"), "")
	}

	// 2. 生成钻石邀请码（平台发放，agent_id为NULL，target_level为3）
	codes := make([]string, 0, req.Count)
	var expireTime sql.NullTime
	if req.ExpireDays > 0 {
		expireTime = sql.NullTime{
			Time:  time.Now().AddDate(0, 0, int(req.ExpireDays)),
			Valid: true,
		}
	}

	err = l.svcCtx.AgentInviteCodeModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
		for i := int64(0); i < req.Count; i++ {
			// 生成8位随机邀请码（大小写字母+数字）
			var code string
			maxRetries := 10 // 最大重试次数
			for retry := 0; retry < maxRetries; retry++ {
				code = tool.Krand(8, tool.KC_RAND_KIND_ALL)
				// 检查邀请码是否已存在
				_, err := l.svcCtx.AgentInviteCodeModel.FindOneByCode(transCtx, code)
				if err != nil {
					if errors.Is(err, model.ErrNotFound) {
						// 邀请码不存在，可以使用
						break
					}
					return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "检查邀请码失败, %v", err)
				}
				// 邀请码已存在，继续生成
				if retry == maxRetries-1 {
					return errors.Wrapf(xerr.NewErrMsg("生成邀请码失败，请重试"), "")
				}
			}

			// 创建邀请码记录（平台发放的钻石邀请码）
            inviteCode := &model.AgentInviteCode{
                Id:          uuid.NewString(),
                Code:        code,
                AgentId:     sql.NullString{Valid: false}, // NULL表示平台发放
                TargetLevel: 3,                            // 钻石代理
                Status:      0,                            // 未使用
                ExpireTime:  expireTime,
                Remark:      sql.NullString{String: req.Remark, Valid: req.Remark != ""},
            }

			_, err := l.svcCtx.AgentInviteCodeModel.Insert(transCtx, session, inviteCode)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建邀请码失败, %v", err)
			}

			codes = append(codes, code)
		}

		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.AdminGenerateDiamondInviteCodeResp{
		Codes: codes,
	}, nil
}
