<?php

namespace Tests\Tenant;

use App\Crm\SendToDealerWebLms;
use App\Facades\Settings;
use App\Listeners\SendReservationToEnquiryIntegrations;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\VehicleReservations\Events\ReservationConfirmedEvent;
use Mtc\VehicleReservations\Reservation;
use Tests\TenantTestCase;

/**
 * Verifies the "Send reservations to CRM integrations" toggle controls whether a
 * confirmed reservation results in an outbound request to a CRM provider.
 */
class SendReservationToEnquiryIntegrationsTest 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 testReservationRequestSentWhenForwardingEnabled()
    {
        $this->setForwarding(true);

        $reservation = $this->makeReservation();

        new SendReservationToEnquiryIntegrations()
            ->handle(new ReservationConfirmedEvent($reservation));

        Http::assertSentCount(1);
        Http::assertSent(fn (Request $request) => Str::contains(
            $request->body(),
            '<ThirdPartyID>R' . $reservation->id . '</ThirdPartyID>'
        ) && Str::contains($request->body(), '<DealerNo>test_dealer_123</DealerNo>'));
    }

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

        new SendReservationToEnquiryIntegrations()
            ->handle(new ReservationConfirmedEvent($this->makeReservation()));

        Http::assertNothingSent();
    }

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

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

        $vehicle = Vehicle::factory()->create([
            'dealership_id' => $dealership->id,
            'is_new' => true,
            'registration_number' => 'ABC123',
        ]);

        return Reservation::factory()->create([
            'vehicle_id' => $vehicle->id,
            'status' => 'confirmed',
            'amount' => 99,
            'crm_reference' => null,
        ]);
    }
}
