package promo

import (
	"context"
	stderrors "errors"

	"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"
	"gorm.io/gorm"
)

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

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

func (l *DeleteRuleLogic) DeleteRule(req *types.DeletePromoRuleRequest) error {
	if _, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id); err != nil {
		if stderrors.Is(err, gorm.ErrRecordNotFound) {
			l.Errorw("[DeletePromoRule] Rule Not Found", logger.Field("id", req.Id))
			return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo rule not found"), "promo rule not found: %d", req.Id)
		}
		l.Errorw("[DeletePromoRule] Find Rule Error", logger.Field("error", err.Error()))
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
	}
	if err := l.svcCtx.PromoModel.DeleteRule(l.ctx, req.Id); err != nil {
		l.Errorw("[DeletePromoRule] Database Error", logger.Field("error", err.Error()))
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo rule error: %v", err.Error())
	}
	if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
		l.Errorw("[DeletePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
	}
	return nil
}
