<?php

namespace App\Observers;

use App\Models\Payment;
use App\Services\PaymentService;
use Illuminate\Support\Facades\Log;

class PaymentObserver
{
    public function __construct(private PaymentService $service) {}

    /**
     * Después de crear: calcula fee y recalcula la venta.
     */
    public function created(Payment $payment): void
    {
        try {
            $this->service->processPayment($payment->fresh());
        } catch (\InvalidArgumentException $e) {
            // Validación de negocio (ej: Takenos solo USD)
            Log::warning("PaymentObserver::created — {$e->getMessage()}", ['payment_id' => $payment->id]);
            throw $e;
        }
    }

    /**
     * Después de actualizar: recalcula fee y venta.
     */
    public function updated(Payment $payment): void
    {
        try {
            $this->service->processPayment($payment->fresh());
        } catch (\InvalidArgumentException $e) {
            Log::warning("PaymentObserver::updated — {$e->getMessage()}", ['payment_id' => $payment->id]);
            throw $e;
        }
    }

    /**
     * Después de eliminar: recalcula la venta sin el pago.
     */
    public function deleted(Payment $payment): void
    {
        // La venta aún existe; recalculamos sin este pago
        $this->service->processPaymentDeleted($payment->sale);
    }
}
