package promo

import (
	"context"

	promomodel "github.com/perfect-panel/server/internal/model/promo"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetUsageListLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetUsageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUsageListLogic {
	return &GetUsageListLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetUsageListLogic) GetUsageList(req *types.GetPromoUsageListRequest) (*types.GetPromoUsageListResponse, error) {
	total, list, err := l.svcCtx.PromoModel.QueryUsageList(l.ctx, promomodel.UsageFilter{
		Page:        int(req.Page),
		Size:        int(req.Size),
		RuleId:      req.RuleId,
		UserId:      req.UserId,
		SubscribeId: req.SubscribeId,
		OrderNo:     req.OrderNo,
	})
	if err != nil {
		l.Errorw("[GetPromoUsageList] Database Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo usage list error: %v", err.Error())
	}
	resp := &types.GetPromoUsageListResponse{
		Total: total,
		List:  make([]types.PromoUsage, 0, len(list)),
	}
	for _, item := range list {
		resp.List = append(resp.List, convertUsage(item))
	}
	return resp, nil
}
