<?php

declare(strict_types=1);

namespace App\Listeners;

use App\Events\CreditStatusSynced;
use App\Services\CollectorSyncService;
use Illuminate\Support\Facades\Log;

/**
 * Escucha el evento interno CreditStatusSynced y delega a CollectorSyncService
 * para mantener el orden de cobro actualizado.
 *
 * Este listener es síncrono (no implementa ShouldQueue) porque la actualización
 * del orden de cobro debe completarse dentro del mismo Job que hizo el sync
 * de estado, garantizando consistencia eventual inmediata.
 */
class CollectorSyncListener
{
    public function __construct(
        protected CollectorSyncService $collectorSyncService,
    ) {}

    public function handle(CreditStatusSynced $event): void
    {
        try {
            $this->collectorSyncService->handleStatusChange(
                $event->credit,
                $event->oldStatus,
                $event->newStatus,
            );
        } catch (\Throwable $e) {
            Log::error('CollectorSyncListener: failed to update collector order', [
                'credit_id' => $event->credit->id,
                'old_status' => $event->oldStatus,
                'new_status' => $event->newStatus,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}
