package usecase

import (
	"context"
	"fmt"

	"gitea.computernetthings.ru/yash/crypto_alert_bot/internal/entities"
	"github.com/shopspring/decimal"
)

func (uc *Usecase) CreateAlert(ctx context.Context, alert *entities.Alert) (entities.AlertID, error) {
	id, err := uc.storage.SaveAlert(ctx, alert)
	if err != nil {
		uc.log.Error("failed to create alert", "alert", alert, "err", err)
		return "", fmt.Errorf("failed to create alert: %w", err)
	}

	return id, nil
}

func (uc *Usecase) Alert(ctx context.Context, alertID entities.AlertID) (*entities.Alert, error) {
	alert, err := uc.storage.AlertByID(ctx, alertID)
	if err != nil {
		uc.log.Error("failed to get alert", "alert_id", alertID, "err", err)
		return nil, fmt.Errorf("failed to get alert: %w", err)
	}

	return alert, nil
}

func (uc *Usecase) Alerts(ctx context.Context, userID entities.UserID, offset, limit int) ([]entities.Alert, error) {
	alerts, err := uc.storage.AlertsByUserID(ctx, userID, offset, limit)
	if err != nil {
		uc.log.Error("failed to get alerts", "user_id", userID, "err", err)
		return nil, fmt.Errorf("failed to get alerts: %w", err)
	}

	return alerts, nil
}

func (uc *Usecase) RemoveAlert(ctx context.Context, alertID entities.AlertID) error {
	if err := uc.storage.DeleteAlert(ctx, alertID); err != nil {
		uc.log.Error("failed to remove alert", "alert_id", alertID, "err", err)
		return fmt.Errorf("failed to remove alert: %w", err)
	}

	return nil
}

func (uc *Usecase) UpdateAlertPrice(ctx context.Context, alertID entities.AlertID, price decimal.Decimal) error {
	if err := uc.storage.UpdateAlertPrice(ctx, alertID, price); err != nil {
		uc.log.Error("failed to update alert price", "alert_id", alertID, "price", price, "err", err)
		return fmt.Errorf("failed to update alert price: %w", err)
	}

	return nil
}

func (uc *Usecase) DisableAlert(ctx context.Context, alertID entities.AlertID) error {
	if err := uc.storage.DisableAlert(ctx, alertID); err != nil {
		uc.log.Error("failed to disable alert", "alert_id", alertID, "err", err)
		return fmt.Errorf("failed to disable alert: %w", err)
	}

	return nil
}
