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

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

func (l *UpdateRuleLogic) UpdateRule(req *types.UpdatePromoRuleRequest) (*types.PromoRule, error) {
	if err := validateRuleInput(req.Type, req.Params, req.Priority, req.StartTime, req.EndTime); err != nil {
		return nil, err
	}
	rule, err := l.svcCtx.PromoModel.FindRule(l.ctx, req.Id)
	if err != nil {
		l.Errorw("[UpdatePromoRule] Find Rule Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "find promo rule error: %v", err.Error())
	}
	params, err := paramsToString(req.Params)
	if err != nil {
		return nil, err
	}
	enabled := rule.Enabled
	if req.Enabled != nil {
		enabled = *req.Enabled
	}
	rule.Name = req.Name
	rule.Type = req.Type
	rule.Params = params
	rule.Priority = req.Priority
	rule.Enabled = enabled
	rule.StartTime = unixPtrToTimePtr(req.StartTime)
	rule.EndTime = unixPtrToTimePtr(req.EndTime)
	if err := l.svcCtx.PromoModel.UpdateRule(l.ctx, rule); err != nil {
		l.Errorw("[UpdatePromoRule] Database Error", logger.Field("error", err.Error()))
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update promo rule error: %v", err.Error())
	}
	if err := l.svcCtx.Redis.Del(l.ctx, ruleCacheKey).Err(); err != nil {
		l.Errorw("[UpdatePromoRule] Delete Cache Error", logger.Field("error", err.Error()))
	}
	resp := convertRule(rule)
	return &resp, nil
}
