package agent

import (
	"context"
	"xingfucha-server/common/ctxdata"
	"xingfucha-server/common/xerr"
	"encoding/json"
	"fmt"
	"time"

	"github.com/pkg/errors"

	"xingfucha-server/app/main/api/internal/svc"
	"xingfucha-server/app/main/api/internal/types"
	"xingfucha-server/app/main/model"

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

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

func NewActivateAgentMembershipLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ActivateAgentMembershipLogic {
	return &ActivateAgentMembershipLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}
func (l *ActivateAgentMembershipLogic) ActivateAgentMembership(req *types.AgentActivateMembershipReq) (resp *types.AgentActivateMembershipResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %v", err)
	}
	// 查询用户代理信息
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败: %v", err)
	}
	// 定义等级顺序映射
	levelOrder := map[string]int{
		"":                        1,
		model.AgentLeveNameNormal: 1,
		model.AgentLeveNameVIP:    2,
		model.AgentLeveNameSVIP:   3,
	}

	// 验证请求等级合法性
	if _, valid := levelOrder[req.Type]; !valid {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "无效的代理等级: %s", req.Type)
	}

	// 如果存在代理记录，进行等级验证
	if agentModel != nil {
		currentLevel, exists := levelOrder[agentModel.LevelName]
		if !exists {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
				"非法的当前代理等级: %s", agentModel.LevelName)
		}

		requestedLevel := levelOrder[req.Type]
		if requestedLevel < currentLevel {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
				"禁止降级操作（当前等级：%s，请求等级：%s）", agentModel.LevelName, req.Type)
		}
		// 同等级视为续费，允许操作
	}
	outTradeNo := "A_" + l.svcCtx.AlipayService.GenerateOutTradeNo()
	redisKey := fmt.Sprintf(types.AgentVipCacheKey, userID, outTradeNo)
	agentVipCache := types.AgentVipCache{Type: req.Type}
	jsonData, err := json.Marshal(agentVipCache)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "序列化代理VIP缓存失败: %v", err)
	}
	cacheErr := l.svcCtx.Redis.SetexCtx(l.ctx, redisKey, string(jsonData), int(2*time.Hour))
	if cacheErr != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "设置缓存失败: %v", cacheErr)
	}
	return &types.AgentActivateMembershipResp{
		Id: outTradeNo,
	}, nil
}
