<?php

namespace Tests\Tenant\Controllers;

use App\Http\Middleware\InitializeTenancyBySiteInRequest;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\SalesChannelRule;
use Mtc\MercuryDataModels\Vehicle;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Tests\TenantTestCase;

class PhyronControllerTest extends TenantTestCase
{
    private string $apiToken = 'test-token';

    private array $bypassMiddleware = [
        InitializeTenancyBySiteInRequest::class,
        InitializeTenancyByPath::class,
    ];

    protected function setUp(): void
    {
        parent::setUp();
        config(['auth.api_auth_token' => $this->apiToken]);
    }

    // --- Stock endpoint ---

    public function test_stock_returns_all_vehicles_when_no_sales_channel_rules()
    {
        Vehicle::factory(5)->create(['is_published' => true]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.stock', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(5, $response->json());
    }

    public function test_stock_excludes_vehicles_from_blacklisted_dealership()
    {
        $excluded = Dealership::factory()->create(['name' => 'Blacklisted Motors']);
        $included = Dealership::factory()->create(['name' => 'Permitted Cars']);

        Vehicle::factory(3)->create(['is_published' => true, 'dealership_id' => $excluded->id]);
        Vehicle::factory(4)->create(['is_published' => true, 'dealership_id' => $included->id]);

        SalesChannelRule::query()->create([
            'channel' => 'phyron',
            'conditions' => [
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Blacklisted Motors',
                    ],
                ],
            ],
        ]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.stock', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(4, $response->json());
        $registrations = collect($response->json())->pluck('full_registration')->toArray();
        $excluded->vehicles->each(
            fn ($vehicle) => $this->assertNotContains($vehicle->vrm_condensed, $registrations)
        );
    }

    public function test_stock_excludes_vehicles_from_multiple_blacklisted_dealerships()
    {
        $excluded_a = Dealership::factory()->create(['name' => 'Blacklisted Motors']);
        $excluded_b = Dealership::factory()->create(['name' => 'Also Blacklisted Cars']);
        $included = Dealership::factory()->create(['name' => 'Permitted Cars']);

        Vehicle::factory(2)->create(['is_published' => true, 'dealership_id' => $excluded_a->id]);
        Vehicle::factory(3)->create(['is_published' => true, 'dealership_id' => $excluded_b->id]);
        Vehicle::factory(5)->create(['is_published' => true, 'dealership_id' => $included->id]);

        SalesChannelRule::query()->create([
            'channel' => 'phyron',
            'conditions' => [
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Blacklisted Motors',
                    ],
                ],
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Also Blacklisted Cars',
                    ],
                ],
            ],
        ]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.stock', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(5, $response->json());
    }

    // --- VDP endpoint ---

    public function test_vdp_returns_all_vehicles_when_no_sales_channel_rules()
    {
        Vehicle::factory(5)->create(['is_published' => true]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.vdp', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(5, $response->json());
    }

    public function test_vdp_excludes_vehicles_from_blacklisted_dealership()
    {
        $excluded = Dealership::factory()->create(['name' => 'Blacklisted Motors']);
        $included = Dealership::factory()->create(['name' => 'Permitted Cars']);

        Vehicle::factory(3)->create(['is_published' => true, 'dealership_id' => $excluded->id]);
        Vehicle::factory(4)->create(['is_published' => true, 'dealership_id' => $included->id]);

        SalesChannelRule::query()->create([
            'channel' => 'phyron',
            'conditions' => [
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Blacklisted Motors',
                    ],
                ],
            ],
        ]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.vdp', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(4, $response->json());
        $registrations = collect($response->json())->pluck('FullRegistration')->toArray();
        $excluded->vehicles->each(
            fn ($vehicle) => $this->assertNotContains(
                str_replace(' ', '', $vehicle->registration_number),
                $registrations
            )
        );
    }

    public function test_vdp_excludes_vehicles_from_multiple_blacklisted_dealerships()
    {
        $excluded_a = Dealership::factory()->create(['name' => 'Blacklisted Motors']);
        $excluded_b = Dealership::factory()->create(['name' => 'Also Blacklisted Cars']);
        $included = Dealership::factory()->create(['name' => 'Permitted Cars']);

        Vehicle::factory(2)->create(['is_published' => true, 'dealership_id' => $excluded_a->id]);
        Vehicle::factory(3)->create(['is_published' => true, 'dealership_id' => $excluded_b->id]);
        Vehicle::factory(5)->create(['is_published' => true, 'dealership_id' => $included->id]);

        SalesChannelRule::query()->create([
            'channel' => 'phyron',
            'conditions' => [
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Blacklisted Motors',
                    ],
                ],
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Also Blacklisted Cars',
                    ],
                ],
            ],
        ]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('phyron.vdp', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(5, $response->json());
    }

    // --- Feed endpoint (/api/feeds/{tenant}/phyron) ---

    public function test_feed_returns_all_vehicles_when_no_sales_channel_rules()
    {
        Vehicle::factory(5)->create(['is_published' => true]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('tenant.feeds.phyron', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(5, $response->json());
    }

    public function test_feed_excludes_vehicles_from_blacklisted_dealership()
    {
        $excluded = Dealership::factory()->create(['name' => 'Blacklisted Motors']);
        $included = Dealership::factory()->create(['name' => 'Permitted Cars']);

        Vehicle::factory(3)->create(['is_published' => true, 'dealership_id' => $excluded->id]);
        Vehicle::factory(4)->create(['is_published' => true, 'dealership_id' => $included->id]);

        SalesChannelRule::query()->create([
            'channel' => 'phyron',
            'conditions' => [
                [
                    'value' => [
                        'type' => 'and',
                        'column' => 'dealership.name',
                        'operator' => '!=',
                        'value' => 'Blacklisted Motors',
                    ],
                ],
            ],
        ]);

        $response = $this->withoutMiddleware($this->bypassMiddleware)
            ->getJson(route('tenant.feeds.phyron', tenant('id')) . '?api_token=' . $this->apiToken);

        $response->assertOk();
        $this->assertCount(4, $response->json());
    }
}
