package admin_agent

import (
	"context"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"

	"github.com/pkg/errors"

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

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

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

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

func (l *AdminGetAgentUpgradeListLogic) AdminGetAgentUpgradeList(req *types.AdminGetAgentUpgradeListReq) (resp *types.AdminGetAgentUpgradeListResp, err error) {
	builder := l.svcCtx.AgentUpgradeModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.AgentId != nil {
		builder = builder.Where("agent_id = ?", *req.AgentId)
	}
	if req.UpgradeType != nil {
		builder = builder.Where("upgrade_type = ?", *req.UpgradeType)
	}
	if req.Status != nil {
		builder = builder.Where("status = ?", *req.Status)
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	upgrades, total, err := l.svcCtx.AgentUpgradeModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询升级记录列表失败, %v", err)
	}

	// 组装响应
	items := make([]types.AgentUpgradeListItem, 0, len(upgrades))
	for _, upgrade := range upgrades {
		items = append(items, types.AgentUpgradeListItem{
			Id:           upgrade.Id,
			AgentId:      upgrade.AgentId,
			FromLevel:    upgrade.FromLevel,
			ToLevel:      upgrade.ToLevel,
			UpgradeType:  upgrade.UpgradeType,
			UpgradeFee:   upgrade.UpgradeFee,
			RebateAmount: upgrade.RebateAmount,
			Status:       upgrade.Status,
			CreateTime:   upgrade.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.AdminGetAgentUpgradeListResp{
		Total: total,
		Items: items,
	}, nil
}
