package promo

import (
	"context"

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

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

func (l *GetRuleListLogic) GetRuleList(req *types.GetPromoRuleListRequest) (*types.GetPromoRuleListResponse, error) {
	total, list, err := l.svcCtx.PromoModel.QueryRuleList(l.ctx, int(req.Page), int(req.Size), req.Type, req.Enabled, req.Search)
	if err != nil {
		l.Errorw("[GetPromoRuleList] Database Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get promo rule list error: %v", err.Error())
	}
	resp := &types.GetPromoRuleListResponse{
		Total: total,
		List:  make([]types.PromoRule, 0, len(list)),
	}
	for _, item := range list {
		resp.List = append(resp.List, convertRule(item))
	}
	return resp, nil
}
