<?php

namespace App\Observers;

use App\Core\Hook\HookBridge;
use App\Models\SavedPaymentMethod;

/**
 * SavedPaymentMethodObserver (PRC-622)
 *
 * Fires the WHMCS-named `CCUpdate` action hook when a saved card is added
 * or its card details change. Observer-level wiring covers ALL creation
 * sites (SavedPaymentMethodController, CheckoutController save-card,
 * PaymentController callback) without per-controller duplication.
 *
 * Hook-only — no communication_events mapping. Context carries only
 * non-sensitive scalars (never token / full PAN).
 */
class SavedPaymentMethodObserver
{
    public function created(SavedPaymentMethod $method): void
    {
        $this->fireCcUpdate($method, 'created');
    }

    public function updated(SavedPaymentMethod $method): void
    {
        // Only card-detail changes count as a "CC update" — default-flag,
        // label or soft-delete status flips are not card data changes.
        if (! $method->wasChanged(['token', 'card_brand', 'last_four', 'expiry_month', 'expiry_year'])) {
            return;
        }

        $this->fireCcUpdate($method, 'updated');
    }

    private function fireCcUpdate(SavedPaymentMethod $method, string $action): void
    {
        app(HookBridge::class)->fireAction('CCUpdate', [
            'userid' => $method->client_id,
            'user_id' => $method->client_id,
            'client_id' => $method->client_id,
            'saved_payment_method_id' => $method->id,
            'gateway' => $method->gateway_slug,
            'card_brand' => $method->card_brand,
            'last_four' => $method->last_four,
            'expiry_month' => $method->expiry_month,
            'expiry_year' => $method->expiry_year,
            'action' => $action,
        ]);
    }
}
