<?php

namespace App\Listeners;

use App\Contracts\ForwardsServiceBookingToCrm;
use App\Events\ServiceBookingConfirmedEvent;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;
use Mtc\Crm\Contracts\EnquiryAction;

class SendServiceBookingToEnquiryIntegrations
{
    public function handle(ServiceBookingConfirmedEvent $event): void
    {
        $this->getProviders()
            ->each(function (ForwardsServiceBookingToCrm $provider, $provider_key) use ($event) {
                try {
                    $provider->sendServiceBooking($event->booking);
                } catch (Exception $exception) {
                    $tenant_id = tenant('id');
                    Log::error("[$tenant_id] Failed to export Service booking to $provider_key", [
                        'message' => $exception->getMessage(),
                        'reservation' => $event->booking->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 ForwardsServiceBookingToCrm);
    }
}
