<?php

namespace App\Listeners;

use App\Contracts\ForwardsServiceBookingToCrm;
use App\Events\ServiceBookingConfirmedEvent;
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;

class SendServiceBookingToEnquiryIntegrations
{
    public function handle(ServiceBookingConfirmedEvent $event): void
    {
        if (Settings::get('crm-forward-service-bookings-enabled', true) !== true) {
            $event->booking->recordProcessing(
                'crm-export',
                ProcessingLog::STATUS_SKIPPED,
                null,
                'Service booking CRM forwarding is disabled in settings.'
            );
            return;
        }

        $this->getProviders()
            ->each(function (ForwardsServiceBookingToCrm $provider, $provider_key) use ($event) {
                try {
                    $success = $provider->sendServiceBooking($event->booking);
                    $event->booking->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 Service booking to $provider_key", [
                        'message' => $exception->getMessage(),
                        'reservation' => $event->booking->id,
                    ]);
                    $event->booking->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 ForwardsServiceBookingToCrm);
    }
}
