<?php

namespace Modules\WhatsApp\Observers;

use App\Transaction;
use Modules\WhatsApp\Entities\Services\WaNotifier;

/**
 * Fires customer/supplier WhatsApp notifications off the core Transaction
 * lifecycle:
 *   - sell, is_quotation        → quotation
 *   - sell, final               → invoice
 *   - sell, shipping_status ∆   → shipment/delivery update
 *   - sell_return, final        → refund/return
 *   - purchase_order, created   → PO sent to supplier
 *
 * Idempotent via WaSender dedupe keys; WaNotifier is self-guarded so a save is
 * never affected.
 */
class TransactionObserver
{
    public function saved(Transaction $transaction): void
    {
        $notifier = new WaNotifier();
        $type = $transaction->type;

        if ($type === 'sell') {
            if ((int) ($transaction->is_quotation ?? 0) === 1) {
                $notifier->quotationSent($transaction);
            } elseif ($transaction->status === 'final') {
                $notifier->invoiceCreated($transaction);
            }

            // Shipment update: only on a real change after creation.
            if (!$transaction->wasRecentlyCreated
                && $transaction->wasChanged('shipping_status')
                && !empty($transaction->shipping_status)) {
                $notifier->shipmentStatus($transaction);
            }
            return;
        }

        if ($type === 'sell_return' && $transaction->status === 'final') {
            $notifier->saleReturned($transaction);
            return;
        }

        if ($type === 'purchase_order' && $transaction->wasRecentlyCreated) {
            $notifier->poSent($transaction);
        }
    }
}
