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

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

func (l *DeletePriceLogic) DeletePrice(req *types.DeletePromoPriceRequest) error {
	price, err := l.svcCtx.PromoModel.FindPrice(l.ctx, req.Id)
	if err != nil {
		if stderrors.Is(err, gorm.ErrRecordNotFound) {
			l.Errorw("[DeletePromoPrice] Price Not Found", logger.Field("id", req.Id))
			return errors.Wrapf(xerr.NewErrCodeMsg(404, "promo price not found"), "promo price not found: %d", req.Id)
		}
		l.Errorw("[DeletePromoPrice] Find Price Error", logger.Field("error", err.Error()))
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo price error: %v", err.Error())
	}
	if err := l.svcCtx.PromoModel.DeletePrice(l.ctx, req.Id); err != nil {
		l.Errorw("[DeletePromoPrice] Database Error", logger.Field("error", err.Error()))
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseDeletedError), "delete promo price error: %v", err.Error())
	}
	if err := l.svcCtx.Redis.Del(l.ctx, subscribePromoCacheKey(price.SubscribeId)).Err(); err != nil {
		l.Errorw("[DeletePromoPrice] Delete Cache Error", logger.Field("error", err.Error()))
	}
	return nil
}
