package agent

import (
	"context"
	"database/sql"
	"qnc-server/common/ctxdata"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-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) {
	claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理信息, %v", err)
	}
	userID := claims.UserId
	userType := claims.UserType
	if userType == model.UserTypeTemp {
		return &types.AgentInfoResp{
			IsAgent: false,
			Status:  3,
		}, nil
	}
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			builder := l.svcCtx.AgentAuditModel.SelectBuilder().Where("user_id = ?", userID).OrderBy("create_time DESC").Limit(1)
			agentAuditList, findAgentAuditErr := l.svcCtx.AgentAuditModel.FindAll(l.ctx, builder, "")

			if findAgentAuditErr != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理信息, %v", findAgentAuditErr)
			}

			if len(agentAuditList) == 0 {
				return &types.AgentInfoResp{
					IsAgent: false,
					Status:  3,
				}, nil
			}

			agentAuditModel := agentAuditList[0]
			return &types.AgentInfoResp{
				IsAgent: false,
				Status:  agentAuditModel.Status,
			}, nil
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理信息, %v", err)
	}
	agent.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)
	}

	IsRealName := false
	agentRealName, err := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agent.Id)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理实名信息失败, %v", err)
	}
	if agentRealName != nil {
		IsRealName = true
	}

	return &types.AgentInfoResp{
		AgentID:    agent.Id,
		Level:      agent.LevelName,
		IsAgent:    true,
		Status:     1,
		Region:     agent.Region,
		Mobile:     agent.Mobile,
		ExpiryTime: agent.MembershipExpiryTime.Time.Format("2006-01-02 15:04:05"),
		IsRealName: IsRealName,
	}, nil
}
