package agent

import (
	"context"
	"sim-server/common/ctxdata"
	"sim-server/common/xerr"
	"sim-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

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

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

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

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

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

	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 不是代理，返回空信息
			return &types.AgentInfoResp{
				AgentId:   "",
				Region:    "",
				Mobile:    "",
				WechatId:  "",
				AgentCode: 0,
			}, nil
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 解密手机号
	mobile, 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)
	}

	// 系统简化：移除实名认证查询
	// 获取微信号
	wechatId := ""
	if agent.WechatId.Valid {
		wechatId = agent.WechatId.String
	}

	// 获取区域
	region := ""
	if agent.Region.Valid {
		region = agent.Region.String
	}

	return &types.AgentInfoResp{
		AgentId:   agent.Id,
		Region:    region,
		Mobile:    mobile,
		WechatId:  wechatId,
		AgentCode: agent.AgentCode,
	}, nil
}
