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

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

func (l *CreateRuleLogic) CreateRule(req *types.CreatePromoRuleRequest) (*types.PromoRule, error) {
	if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
		return nil, err
	}
	params, err := paramsToString(req.Params)
	if err != nil {
		return nil, err
	}
	enabled := true
	if req.Enabled != nil {
		enabled = *req.Enabled
	}
	rule := &promomodel.Rule{
		Name:      req.Name,
		Type:      req.Type,
		Params:    params,
		Priority:  req.Priority,
		Enabled:   enabled,
		StartTime: unixPtrToTimePtr(req.StartTime),
		EndTime:   unixPtrToTimePtr(req.EndTime),
	}
	if err := l.svcCtx.PromoModel.InsertRule(l.ctx, rule); err != nil {
		l.Errorw("[CreatePromoRule] Database Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseInsertError), "create promo rule error: %v", err.Error())
	}
	if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
		l.Errorw("[CreatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
	}
	resp := convertRule(rule)
	return &resp, nil
}
