<?php

namespace App\Listeners;

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

class SendReservationToEnquiryIntegrations
{
    public function handle(ReservationConfirmedEvent $event): void
    {
        if (!empty($event->reservation->crm_reference)) {
            // already processed
            return;
        }

        if (Settings::get('crm-forward-reservations-enabled', true) !== true) {
            $event->reservation->recordProcessing(
                'crm-export',
                ProcessingLog::STATUS_SKIPPED,
                null,
                'Reservation CRM forwarding is disabled in settings.'
            );
            return;
        }

        $this->getProviders()
            ->each(function (ForwardsReservationToCrm $provider, $provider_key) use ($event) {
                try {
                    $success = $provider->sendReservation($event->reservation);
                    $event->reservation->recordProcessing(
                        'crm-export',
                        $success ? ProcessingLog::STATUS_SUCCESS : ProcessingLog::STATUS_FAILED,
                        $provider_key,
                        $success ? $provider->successDetails() : $provider->failureReason()
                    );
                } 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,
                    ]);
                    $event->reservation->recordProcessing(
                        'crm-export',
                        ProcessingLog::STATUS_FAILED,
                        $provider_key,
                        $exception->getMessage()
                    );
                }
            });
    }

    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);
    }
}
