package agent

import (
	"context"
	"qnc-server/app/main/model"
	"qnc-server/common/ctxdata"
	"qnc-server/common/globalkey"
	"qnc-server/common/xerr"

	"github.com/pkg/errors"

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

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

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

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

func (l *GetInviteCodeListLogic) GetInviteCodeList(req *types.GetInviteCodeListReq) (resp *types.GetInviteCodeListResp, err error) {
	// 1. 获取当前代理信息
	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 nil, errors.Wrapf(xerr.NewErrMsg("您不是代理"), "")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 2. 构建查询条件
	builder := l.svcCtx.AgentInviteCodeModel.SelectBuilder().
		Where("agent_id = ? AND del_state = ?", agent.Id, globalkey.DelStateNo)

	if req.Status >= 0 {
		builder = builder.Where("status = ?", req.Status)
	}

	// 3. 分页查询
	list, total, err := l.svcCtx.AgentInviteCodeModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询邀请码列表失败, %v", err)
	}

	// 4. 格式化返回数据
	items := make([]types.InviteCodeItem, 0, len(list))
	for _, v := range list {
		item := types.InviteCodeItem{
			Id:          v.Id,
			Code:        v.Code,
			TargetLevel: v.TargetLevel,
			Status:      v.Status,
			CreateTime:  v.CreateTime.Format("2006-01-02 15:04:05"),
		}

		if v.UsedTime.Valid {
			item.UsedTime = v.UsedTime.Time.Format("2006-01-02 15:04:05")
		}
		if v.ExpireTime.Valid {
			item.ExpireTime = v.ExpireTime.Time.Format("2006-01-02 15:04:05")
		}
		if v.Remark.Valid {
			item.Remark = v.Remark.String
		}

		items = append(items, item)
	}

	return &types.GetInviteCodeListResp{
		Total: total,
		List:  items,
	}, nil
}
