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 GetPriceListLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *GetPriceListLogic) GetPriceList(req *types.GetPromoPriceListRequest) (*types.GetPromoPriceListResponse, error) {
	total, list, err := l.svcCtx.PromoModel.QueryPriceList(l.ctx, promomodel.PriceFilter{
		Page:        int(req.Page),
		Size:        int(req.Size),
		RuleId:      req.RuleId,
		SubscribeId: req.SubscribeId,
	})
	if err != nil {
		l.Errorw("[GetPromoPriceList] Database Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo price list error: %v", err.Error())
	}
	resp := &types.GetPromoPriceListResponse{
		Total: total,
		List:  make([]types.PromoPrice, 0, len(list)),
	}
	for _, item := range list {
		resp.List = append(resp.List, convertPrice(item))
	}
	return resp, nil
}
