<?php

namespace Tests\Tenant\Controllers;

use App\Facades\Settings;
use App\Http\Controllers\FeedController;
use App\Http\Middleware\ApiAuthenticatedRequest;
use App\Http\Middleware\InitializeTenancyBySiteInRequest;
use Mtc\Crm\Models\Enquiry;
use Mtc\Crm\Models\EnquiryObject;
use Mtc\Crm\Models\Form;
use Mtc\Crm\Models\FormQuestion;
use Mtc\MercuryDataModels\Booking;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleValuation;
use Mtc\VehicleReservations\Reservation;
use Tests\TenantTestCase;

class FeedControllerTest extends TenantTestCase
{
    private array $excludedMiddlewares = [
        InitializeTenancyBySiteInRequest::class,
        ApiAuthenticatedRequest::class,
    ];

    /**
     * Helper to setup Enquiry with related Vehicle, Form, Questions
     */
    private function createEnquiryWithVehicle(): Enquiry
    {
        $vehicle = Vehicle::factory()->create([
            'odometer_km' => 50000,
            'odometer_mi' => 31000,
        ]);
        $form = Form::factory()->create(['name' => 'Vehicle Enquiry']);
        $q1 = FormQuestion::factory()->create(['data' => ["ms-dynamics-field" => "first_name"]]);
        $q2 = FormQuestion::factory()->create(['data' => ["ms-dynamics-field" => "last_name"]]);

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'reason_type' => 'vehicle',
            'reason_id' => $vehicle->id,
            'email' => 'carlover@example.com',
            'details' => [
                $q1->id => [
                    'answer' => 'Peter'
                ],
                $q2->id => [
                    'answer' => 'Parker'
                ],
            ],
            'data' => [
                'questions' => [
                    $q1->id => [
                        'component' => 'TextField',
                        'componentName' => 'TextField',
                        'meta' => null
                    ],
                    $q2->id => [
                        'component' => 'TextField',
                        'componentName' => 'TextField',
                        'meta' => null
                    ],
                ]
            ]
        ]);

        EnquiryObject::factory()->create([
            'enquiry_id' => $enquiry->id,
            'object_type' => 'vehicle',
            'object_id' => $vehicle->id,
        ]);

        return $enquiry;
    }

    // --- STORM ENQUIRIES ENDPOINT TESTS ---

    public function testStormEnquiriesReturnsCorrectItems()
    {
        $enquiry = $this->createEnquiryWithVehicle();
        $booking = Booking::factory()->create(['uuid' => '1234567890']);
        $reservation = Reservation::factory()->create([]);

        $response = $this->withoutMiddleware($this->excludedMiddlewares)
            ->getJson(route('storm-enquiries', tenant('id')));
        $response->assertStatus(200);

        $json = $response->json();

        // Assert _meta
        $this->assertEquals(3, $json['_meta']['totalCount']);
        $this->assertEquals(15, $json['_meta']['perPage']);
        $this->assertEquals(1, $json['_meta']['pageCount']);
        $this->assertEquals(1, $json['_meta']['currentPage']);

        // Assert items
        $this->assertCount(3, $json['items']);
        foreach ($json['items'] as $item) {
            $this->assertArrayHasKey('_links', $item);
            $this->assertArrayHasKey('context', $item);
            $this->assertArrayHasKey('date_submitted', $item);
            $this->assertArrayHasKey('dealer', $item);
            $this->assertArrayHasKey('form', $item);
            $this->assertArrayHasKey('guid', $item);
            $this->assertArrayHasKey('type', $item);
        }

        // Assert order
        $dates = array_column($json['items'], 'date_submitted');
        $this->assertTrue($dates[0] >= $dates[1] && $dates[1] >= $dates[2]);

        // Assert type names
        $types = array_column($json['items'], 'type');
        $typeNames = array_column($types, 'name');
        $this->assertContains('Vehicle Enquiry', $typeNames);
        $this->assertContains('Vehicle Reservation', $typeNames);
        $this->assertContains('Service Booking', $typeNames);
    }

    public function testStormEnquiriesPaginationWorks()
    {
        Enquiry::factory()->count(20)->create();
        $response = $this->withoutMiddleware($this->excludedMiddlewares)
            ->getJson(route('storm-enquiries', tenant('id')) . '?page=2');
        $json = $response->json();

        $this->assertEquals(20, $json['_meta']['totalCount']);
        $this->assertEquals(15, $json['_meta']['perPage']);
        $this->assertEquals(2, $json['_meta']['pageCount']);
        $this->assertEquals(2, $json['_meta']['currentPage']);
        $this->assertCount(5, $json['items']);
    }

    public function testStormEnquiriesFilterByDateWorks()
    {
        Booking::factory()->create(['created_at' => now()->subDays(10), 'uuid' => '1234567890']);
        Reservation::factory()->create(['created_at' => now()->subDays(10)]);
        Enquiry::factory()->create(['created_at' => now()->subDays(10)]);

        $recentEnquiry = Enquiry::factory()->create(['created_at' => now()->subDays(1)]);

        $response = $this->withoutMiddleware($this->excludedMiddlewares)
            ->getJson(
                route('storm-enquiries', tenant('id')) .
                '?From=' . now()->subDays(2)->format('Y-m-d')
            );
        $json = $response->json();

        $this->assertCount(1, $json['items']);
        $this->assertEquals($recentEnquiry->id, $json['items'][0]['guid']);
    }

    public function testStormEnquiriesLinksRetainQueryParameters()
    {
        Enquiry::factory()->count(20)->create();

        $from = now()->subDays(5)->format('Y-m-d\TH:i:s');
        $to = now()->format('Y-m-d\TH:i:s');

        $response = $this->withoutMiddleware($this->excludedMiddlewares)
            ->getJson(
                route('storm-enquiries', tenant('id')) .
                '?From=' . $from . '&To=' . $to
            );

        $json = $response->json();

        $this->assertStringContainsString('From=' . urlencode($from), $json['_links']['self']);
        $this->assertStringContainsString('To=' . urlencode($to), $json['_links']['self']);
        $this->assertStringContainsString('From=' . urlencode($from), $json['_links']['first']);
        $this->assertStringContainsString('To=' . urlencode($to), $json['_links']['first']);
        $this->assertStringContainsString('From=' . urlencode($from), $json['_links']['last']);
        $this->assertStringContainsString('To=' . urlencode($to), $json['_links']['last']);

        if ($json['_links']['next']) {
            $this->assertStringContainsString('From=' . urlencode($from), $json['_links']['next']);
            $this->assertStringContainsString('To=' . urlencode($to), $json['_links']['next']);
        }
    }

    // ---  STORM ENQUIRY RESOURCE TESTS ---
    public function testStormEnquiryResourceEnquiry()
    {
        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'distance measurement',
            'config_key' => 'automotive-distance_measurement',
            'value' => 'km',
            'type' => 'string',
        ]);

        $enquiry = $this->createEnquiryWithVehicle();
        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id);

        $this->assertInstanceOf(\App\Http\Resources\StormEnquiryItemResource::class, $response);

        $data = $response->resolve();
        $this->assertEquals('Peter', $data['form']['customer']['first_name']);
        $this->assertEquals('Parker', $data['form']['customer']['last_name']);
        $this->assertEquals('Vehicle Enquiry', $data['type']['name']);
        $this->assertNotNull($data['context']['vehicle']);
        $this->assertEquals('km', $data['context']['vehicle']['odometer']['unit']);
        $this->assertEquals(50000, $data['context']['vehicle']['odometer']['current']);
    }

    public function testStormEnquiryResourceBooking()
    {
        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'distance measurement',
            'config_key' => 'automotive-distance_measurement',
            'value' => 'mi',
            'type' => 'string',
        ]);

        $booking = Booking::factory()->create([
            'uuid' => '123456',
            'mileage' => 15000,
            'registration_number' => 'ABC123',
        ]);

        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'booking', $booking->id);

        $this->assertInstanceOf(\App\Http\Resources\StormEnquiryItemResource::class, $response);

        $data = $response->resolve();
        $this->assertEquals('Service Booking', $data['type']['name']);
        $this->assertEquals('ABC123', $data['context']['vehicle']['vrm']);
        $this->assertEquals(15000, $data['context']['vehicle']['odometer']['current']);
        $this->assertEquals('mi', $data['context']['vehicle']['odometer']['unit']);

        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'distance measurement',
            'config_key' => 'automotive-distance_measurement',
            'value' => 'km',
            'type' => 'string',
        ]);

        $responseKm = $controller->stormEnquiry(request(), 'booking', $booking->id);
        $dataKm = $responseKm->resolve();

        $this->assertEquals('km', $dataKm['context']['vehicle']['odometer']['unit']);
    }

    public function testStormEnquiryResourceReservation()
    {
        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'distance measurement',
            'config_key' => 'automotive-distance_measurement',
            'value' => 'km',
            'type' => 'string',
        ]);

        $vehicle = Vehicle::factory()->create([
            'odometer_km' => null,
            'odometer_mi' => 10000,
        ]);

        $reservation = Reservation::factory()->create([
            'amount' => 200,
            'vehicle_id' => $vehicle->id,
            'first_name' => 'John',
            'last_name' => 'Doe',
            'contact_number' => '1234567890',
            'email' => 'john@example.com',
        ]);

        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'reservation', $reservation->id);

        $this->assertInstanceOf(\App\Http\Resources\StormEnquiryItemResource::class, $response);

        $data = $response->resolve();
        $this->assertEquals('Vehicle Reservation', $data['type']['name']);
        $this->assertEquals(200, $data['form']['enquiry']['offer_price']);
        $this->assertEquals('John', $data['form']['customer']['first_name']);
        $this->assertEquals('Doe', $data['form']['customer']['last_name']);
        $this->assertEquals('km', $data['context']['vehicle']['odometer']['unit']);
        $this->assertEquals(16093, $data['context']['vehicle']['odometer']['current']);
    }

    public function testStormEnquiryNotFound()
    {
        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'enquiry', 99999);
        $this->assertEquals(404, $response->getStatusCode());
    }

    public function testStormEnquiryContactMethodsParsedCorrectly()
    {
        $vehicle = Vehicle::factory()->create();
        $form = Form::factory()->create(['name' => 'Contact Enquiry']);
        $q1 = FormQuestion::factory()->create(['data' => ['ms-dynamics-field' => 'first_name']]);
        $q2 = FormQuestion::factory()->create(['data' => ['ms-dynamics-field' => 'contact_methods']]);

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $q1->id => ['answer' => 'Jane'],
                $q2->id => ['answer' => 'email,phone,sms'],
            ],
            'data' => [
                'questions' => [
                    $q1->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                    $q2->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                ],
            ],
        ]);

        EnquiryObject::factory()->create([
            'enquiry_id' => $enquiry->id,
            'object_type' => 'vehicle',
            'object_id' => $vehicle->id,
        ]);

        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id);
        $data = $response->resolve();

        $prefs = $data['form']['customer']['marketing_preferences']['first_party'];
        $this->assertTrue($prefs['email']);
        $this->assertTrue($prefs['phone']);
        $this->assertTrue($prefs['sms']);
        $this->assertFalse($prefs['post']);
    }

    public function testStormEnquiryEmptyContactMethodsDoesNotError()
    {
        $vehicle = Vehicle::factory()->create();
        $form = Form::factory()->create(['name' => 'Simple Enquiry']);
        $q1 = FormQuestion::factory()->create(['data' => ['ms-dynamics-field' => 'first_name']]);
        $q2 = FormQuestion::factory()->create(['data' => ['ms-dynamics-field' => 'contact_methods']]);

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $q1->id => ['answer' => 'Jane'],
                $q2->id => ['answer' => ''],
            ],
            'data' => [
                'questions' => [
                    $q1->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                    $q2->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                ],
            ],
        ]);

        EnquiryObject::factory()->create([
            'enquiry_id' => $enquiry->id,
            'object_type' => 'vehicle',
            'object_id' => $vehicle->id,
        ]);

        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id);
        $data = $response->resolve();

        $prefs = $data['form']['customer']['marketing_preferences']['first_party'];
        $this->assertFalse($prefs['email']);
        $this->assertFalse($prefs['phone']);
        $this->assertFalse($prefs['sms']);
        $this->assertFalse($prefs['post']);
    }

    public function testStormEnquiryPopulatesCustomerVehicleFromFormAnswers(): void
    {
        Settings::make([
            'tab' => 'foo-baz',
            'section' => 'lorem',
            'group' => 'ipsum',
            'name' => 'distance measurement',
            'config_key' => 'automotive-distance_measurement',
            'value' => 'mi',
            'type' => 'string',
        ]);

        $form = Form::factory()->create(['name' => 'Service Enquiry']);
        $qReg = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_registration']]
        );
        $qMake = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_make']]
        );
        $qModel = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_model']]
        );
        $qMileage = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_mileage']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qReg->id    => ['answer' => '172-KE-462'],
                $qMake->id   => ['answer' => 'Nissan'],
                $qModel->id  => ['answer' => 'Micra'],
                $qMileage->id => ['answer' => '162000'],
            ],
            'data' => [
                'questions' => [
                    $qReg->id    => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                    $qMake->id   => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                    $qModel->id  => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                    $qMileage->id => ['component' => 'NumberField', 'componentName' => 'NumberField', 'meta' => null],
                ],
            ],
        ]);

        $controller = new FeedController();
        $response = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id);
        $data = $response->resolve();

        $customerVehicle = $data['form']['customer']['vehicle'];

        $this->assertNotNull($customerVehicle, 'form.customer.vehicle should be populated from form answers');
        $this->assertSame('172-KE-462', $customerVehicle['vrm']);
        $this->assertSame('Nissan', $customerVehicle['manufacturer']);
        $this->assertSame('Micra', $customerVehicle['model']);
        $this->assertSame(162000, $customerVehicle['odometer']['current']);
        $this->assertSame('mi', $customerVehicle['odometer']['unit']);
        $this->assertArrayNotHasKey('fuel_type', $customerVehicle);
        $this->assertArrayNotHasKey('transmission_type', $customerVehicle);
        $this->assertArrayNotHasKey('condition', $customerVehicle);
        $this->assertArrayNotHasKey('derivative', $customerVehicle);
        $this->assertArrayNotHasKey('engine_size_litres', $customerVehicle);
        $this->assertArrayNotHasKey('variant', $customerVehicle);
        $this->assertArrayNotHasKey('dealer', $customerVehicle);
    }

    public function testStormEnquiryCustomerVehicleIncludesDueDatesAndOmitsUnmappedKeys(): void
    {
        $form = Form::factory()->create(['name' => 'Service Enquiry']);
        $qService = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_service_due_date']]
        );
        $qMot = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_mot_due_date']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qService->id => ['answer' => '2026-04-22T09:55:00.000Z'],
                $qMot->id     => ['answer' => '2026-08-25T09:55:00.000Z'],
            ],
            'data' => [
                'questions' => [
                    $qService->id => ['component' => 'DateField', 'componentName' => 'DateField', 'meta' => null],
                    $qMot->id     => ['component' => 'DateField', 'componentName' => 'DateField', 'meta' => null],
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();
        $v = $data['form']['customer']['vehicle'];

        $this->assertSame('2026-04-22T09:55:00.000Z', $v['next_service_date']);
        $this->assertSame('2026-08-25T09:55:00.000Z', $v['next_mot_date']);
        $this->assertArrayNotHasKey('vrm', $v);
        $this->assertArrayNotHasKey('manufacturer', $v);
        $this->assertArrayNotHasKey('model', $v);
        $this->assertArrayNotHasKey('odometer', $v);
    }

    public function testStormEnquiryCustomerVehicleIsNullWhenNoRelevantAnswers(): void
    {
        $form = Form::factory()->create(['name' => 'Finance Enquiry']);
        $qName = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'first_name']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qName->id => ['answer' => 'Alex'],
            ],
            'data' => [
                'questions' => [
                    $qName->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertNull($data['form']['customer']['vehicle']);
    }

    public function testStormEnquiryPreferredDateFallsBackToCustomerVehicleServiceDueDate(): void
    {
        $form = Form::factory()->create(['name' => 'Service Enquiry']);
        $qService = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_service_due_date']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qService->id => ['answer' => '2026-04-22T09:55:00.000Z'],
            ],
            'data' => [
                'questions' => [
                    $qService->id => ['component' => 'DateField', 'componentName' => 'DateField', 'meta' => null],
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertSame('2026-04-22T09:55:00.000Z', $data['form']['enquiry']['preferred_date']);
        $this->assertSame('2026-04-22T09:55:00.000Z', $data['form']['customer']['vehicle']['next_service_date']);
    }

    public function testStormEnquiryExplicitPreferredDateMappingWinsOverFallback(): void
    {
        $form = Form::factory()->create(['name' => 'Service Enquiry']);
        $qPreferred = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'preferred_date']]
        );
        $qService = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_service_due_date']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qPreferred->id => ['answer' => '2026-05-01T10:00:00.000Z'],
                $qService->id   => ['answer' => '2026-04-22T09:55:00.000Z'],
            ],
            'data' => [
                'questions' => [
                    $qPreferred->id => ['component' => 'DateField', 'componentName' => 'DateField', 'meta' => null],
                    $qService->id   => ['component' => 'DateField', 'componentName' => 'DateField', 'meta' => null],
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertSame('2026-05-01T10:00:00.000Z', $data['form']['enquiry']['preferred_date']);
        $this->assertSame('2026-04-22T09:55:00.000Z', $data['form']['customer']['vehicle']['next_service_date']);
    }

    public function testStormEnquiryValuationStillWinsOverFormCustomerVehicleParams(): void
    {
        $valuation = VehicleValuation::factory()->create([
            'registration' => 'VAL123',
            'make' => 'Ford',
            'model' => 'Fiesta',
            'mileage' => 40000,
        ]);

        $form = Form::factory()->create(['name' => 'Trade-in Enquiry']);
        $qReg = FormQuestion::factory()->create(
            ['data' => ['ms-dynamics-field' => 'customer_vehicle_registration']]
        );

        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'details' => [
                $qReg->id => ['answer' => 'SHOULDNOTAPPEAR'],
            ],
            'data' => [
                'questions' => [
                    $qReg->id => ['component' => 'TextField', 'componentName' => 'TextField', 'meta' => null],
                ],
            ],
        ]);

        EnquiryObject::factory()->create([
            'enquiry_id' => $enquiry->id,
            'object_type' => 'valuation',
            'object_id' => $valuation->id,
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertSame('VAL123', $data['form']['customer']['vehicle']['vrm']);
    }

    public function testStormEnquiryForwardsGclidAndUtmFromMeta(): void
    {
        $form = Form::factory()->create(['name' => 'Vehicle Enquiry']);
        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'data' => [
                'meta' => [
                    'gclid'        => 'CjwKgclid-ABC',
                    'utm_source'   => 'google',
                    'utm_medium'   => 'cpc',
                    'utm_campaign' => 'spring-sale',
                    'utm_content'  => 'banner-a',
                    'utm_term'     => 'used+cars',
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertSame('CjwKgclid-ABC', $data['form']['enquiry']['gclid']);
        $this->assertSame('google', $data['form']['enquiry']['utm_source']);
        $this->assertSame('cpc', $data['form']['enquiry']['utm_medium']);
        $this->assertSame('spring-sale', $data['form']['enquiry']['utm_campaign']);
        $this->assertSame('banner-a', $data['form']['enquiry']['utm_content']);
        $this->assertSame('used+cars', $data['form']['enquiry']['utm_term']);
    }

    public function testStormEnquiryTrackingFieldsNullWhenMetaAbsent(): void
    {
        $form = Form::factory()->create(['name' => 'Vehicle Enquiry']);
        $enquiry = Enquiry::factory()->create([
            'form_id' => $form->id,
            'data' => ['questions' => []],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'enquiry', $enquiry->id)->resolve();

        $this->assertNull($data['form']['enquiry']['gclid']);
        $this->assertNull($data['form']['enquiry']['utm_source']);
        $this->assertNull($data['form']['enquiry']['utm_medium']);
        $this->assertNull($data['form']['enquiry']['utm_campaign']);
        $this->assertNull($data['form']['enquiry']['utm_content']);
        $this->assertNull($data['form']['enquiry']['utm_term']);
    }

    public function testStormBookingForwardsGclidAndUtmFromMeta(): void
    {
        $booking = Booking::factory()->create([
            'uuid' => 'booking-utm-1',
            'data' => [
                'meta' => [
                    'gclid'        => 'CjwKbooking-XYZ',
                    'utm_source'   => 'facebook',
                    'utm_medium'   => 'social',
                    'utm_campaign' => 'service-promo',
                    'utm_content'  => 'video-1',
                    'utm_term'     => 'mot+near+me',
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'booking', $booking->id)->resolve();

        $this->assertSame('CjwKbooking-XYZ', $data['form']['enquiry']['gclid']);
        $this->assertSame('facebook', $data['form']['enquiry']['utm_source']);
        $this->assertSame('social', $data['form']['enquiry']['utm_medium']);
        $this->assertSame('service-promo', $data['form']['enquiry']['utm_campaign']);
        $this->assertSame('video-1', $data['form']['enquiry']['utm_content']);
        $this->assertSame('mot+near+me', $data['form']['enquiry']['utm_term']);
    }

    public function testStormBookingTrackingFieldsNullWhenMetaAbsent(): void
    {
        $booking = Booking::factory()->create(['uuid' => 'booking-utm-2']);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'booking', $booking->id)->resolve();

        $this->assertNull($data['form']['enquiry']['gclid']);
        $this->assertNull($data['form']['enquiry']['utm_source']);
        $this->assertNull($data['form']['enquiry']['utm_medium']);
        $this->assertNull($data['form']['enquiry']['utm_campaign']);
        $this->assertNull($data['form']['enquiry']['utm_content']);
        $this->assertNull($data['form']['enquiry']['utm_term']);
    }

    public function testStormReservationForwardsGclidAndUtmFromMeta(): void
    {
        $reservation = Reservation::factory()->create([
            'data' => [
                'meta' => [
                    'gclid'        => 'CjwKreservation-Q1',
                    'utm_source'   => 'bing',
                    'utm_medium'   => 'email',
                    'utm_campaign' => 'newsletter',
                    'utm_content'  => 'cta-top',
                    'utm_term'     => 'new+vehicle',
                ],
            ],
        ]);

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'reservation', $reservation->id)->resolve();

        $this->assertSame('CjwKreservation-Q1', $data['form']['enquiry']['gclid']);
        $this->assertSame('bing', $data['form']['enquiry']['utm_source']);
        $this->assertSame('email', $data['form']['enquiry']['utm_medium']);
        $this->assertSame('newsletter', $data['form']['enquiry']['utm_campaign']);
        $this->assertSame('cta-top', $data['form']['enquiry']['utm_content']);
        $this->assertSame('new+vehicle', $data['form']['enquiry']['utm_term']);
    }

    public function testStormReservationTrackingFieldsNullWhenMetaAbsent(): void
    {
        $reservation = Reservation::factory()->create();

        $controller = new FeedController();
        $data = $controller->stormEnquiry(request(), 'reservation', $reservation->id)->resolve();

        $this->assertNull($data['form']['enquiry']['gclid']);
        $this->assertNull($data['form']['enquiry']['utm_source']);
        $this->assertNull($data['form']['enquiry']['utm_medium']);
        $this->assertNull($data['form']['enquiry']['utm_campaign']);
        $this->assertNull($data['form']['enquiry']['utm_content']);
        $this->assertNull($data['form']['enquiry']['utm_term']);
    }
}
