<?php

namespace App\Listeners;

use App\Contracts\ForwardsReservationToCrm;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Mtc\Crm\Contracts\EnquiryAction;
use Mtc\VehicleReservations\Events\ReservationConfirmedEvent;

class SendReservationToEnquiryIntegrations
{
    public function handle(ReservationConfirmedEvent $event): void
    {
        if (!empty($event->reservation->crm_reference)) {
            // already processed
            return;
        }
        $this->getProviders()
            ->each(function (ForwardsReservationToCrm $provider, $provider_key) use ($event) {
                try {
                    $provider->sendReservation($event->reservation);
                } catch (Exception $exception) {
                    $tenant_id = tenant('id');
                    Log::error("[$tenant_id] Failed to export Reservation to $provider_key", [
                        'message' => $exception->getMessage(),
                        'reservation' => $event->reservation->id,
                    ]);
                }
            });
    }

    private function getProviders(): Collection
    {
        return collect(config('crm.form_actions', []))
            ->map(fn ($class) => App::make($class))
            ->filter(fn (EnquiryAction $action) => $action->enabled())
            ->filter(fn (EnquiryAction $action) => $action instanceof ForwardsReservationToCrm);
    }
}
