<?php

namespace Tests\Tenant;

use App\Crm\SendToDealerWebLms;
use App\Events\ServiceBookingConfirmedEvent;
use App\Facades\Settings;
use App\Listeners\SendServiceBookingToEnquiryIntegrations;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Booking;
use Mtc\MercuryDataModels\BookingDeliveryOption;
use Mtc\MercuryDataModels\Dealership;
use Tests\TenantTestCase;

/**
 * Verifies the "Send service bookings to CRM integrations" toggle controls whether
 * a confirmed service booking results in an outbound request to a CRM provider.
 */
class SendServiceBookingToEnquiryIntegrationsTest extends TenantTestCase
{
    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();

        // Fail loudly if any non-faked outbound request slips through.
        Http::preventStrayRequests();

        // Route CRM forwarding through the real DealerWeb provider only.
        Config::set('crm.form_actions', [
            'send-to-dealer-web-lms' => SendToDealerWebLms::class,
        ]);

        Settings::make([
            'tab' => 'CRM',
            'section' => 'Integrations',
            'group' => 'Dealer Web LMS',
            'name' => 'Enabled',
            'config_key' => 'dealerweblms-crm-enabled',
            'type' => 'boolean',
            'value' => true,
        ]);
        Settings::make([
            'tab' => 'CRM',
            'section' => 'Integrations',
            'group' => 'Dealer Web LMS',
            'name' => 'Dealer Web Endpoint',
            'config_key' => 'dealerweblms-endpoint',
            'type' => 'string',
            'value' => '*',
        ]);

        Http::fake([
            '*' => Http::response('<AddLeadResult>
                <CustomerID>123456</CustomerID>
                <ErrorCode>0</ErrorCode>
                <ErrorMessage />
            </AddLeadResult>', 200),
        ]);
    }

    public function testServiceBookingRequestSentWhenForwardingEnabled()
    {
        $this->setForwarding(true);

        new SendServiceBookingToEnquiryIntegrations()
            ->handle(new ServiceBookingConfirmedEvent($this->makeBooking()));

        Http::assertSentCount(1);
        Http::assertSent(fn (Request $request) => Str::contains($request->body(), '<Forename>John</Forename>')
            && Str::contains($request->body(), '<DealerNo>test_dealer_123</DealerNo>'));
    }

    public function testNoServiceBookingRequestSentWhenForwardingDisabled()
    {
        $this->setForwarding(false);

        new SendServiceBookingToEnquiryIntegrations()
            ->handle(new ServiceBookingConfirmedEvent($this->makeBooking()));

        Http::assertNothingSent();
    }

    private function setForwarding(bool $enabled): void
    {
        Settings::make([
            'tab' => 'CRM',
            'section' => 'Integrations',
            'group' => 'CRM Forwarding',
            'name' => 'Send service bookings to CRM integrations',
            'config_key' => 'crm-forward-service-bookings-enabled',
            'type' => 'boolean',
            'value' => $enabled,
        ]);
    }

    private function makeBooking(): Booking
    {
        $dealership = Dealership::factory()->create([
            'data' => [
                'dealerweb-dealer-id' => 'test_dealer_123',
            ],
        ]);

        $deliveryOption = BookingDeliveryOption::query()->create([
            'name' => 'foo',
            'description' => 'We collect and deliver your vehicle',
            'price' => 25.00,
        ]);

        return Booking::factory()->create([
            'uuid' => Str::uuid()->toString(),
            'first_name' => 'John',
            'last_name' => 'Smith',
            'email' => 'john.smith@example.com',
            'phone_number' => '07700900123',
            'registration_number' => 'AB12CDE',
            'mileage' => 45000,
            'location_id' => $dealership->id,
            'delivery_option_id' => $deliveryOption->id,
            'booking_time' => '2024-03-15 10:00:00',
            'vehicle_data' => [
                'make' => 'Ford',
                'model' => 'Focus',
            ],
            'data' => [],
        ]);
    }
}
