<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Modules\Stock\Skupenet;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;

class SkupenetFeatureExtractionTest extends TenantTestCase
{
    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();

        Queue::fake();
        Settings::make([
            'tab' => 'foo',
            'section' => 'foo',
            'group' => 'foo',
            'name' => 'foo',
            'config_key' => 'app-details-currency',
            'value' => 'GBP',
            'type' => 'string'
        ]);
        Dealership::factory()->create(['data' => ['skupenet-location-id' => 123]]);
    }

    public function testTailBlockExtractionRemainsTheDefault()
    {
        $this->importWithDescription(
            "Intro paragraph\n\nAlloys\nBluetooth\nCruise control\nClimate control\nParking sensors\nHeated seats"
        );

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEquals(6, $vehicle->features()->count());
        $this->assertEquals('Intro paragraph', $vehicle->description);
    }

    public function testBulletModeExtractsBulletsAnywhereAndStripsHeading()
    {
        $this->enableBulletMode();

        // Polo-style: features mid-text, benefits and call to action after them
        $this->importWithDescription(
            "DESCRIPTION: \n\n Intro text about the car.\n\n KEY FEATURES\n\n "
            . "• Digital cockpit\n • Apple CarPlay\n • Reverse parking sensors\n • Alloy wheels\n \n\n "
            . "DEALERSHIP BENEFITS \n\n Trade ins welcome\n\n Call our sales team."
        );

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEqualsCanonicalizing(
            ['Digital cockpit', 'Apple CarPlay', 'Reverse parking sensors', 'Alloy wheels'],
            $vehicle->features()->pluck('name')->toArray()
        );
        $this->assertStringNotContainsString('•', $vehicle->description);
        $this->assertStringNotContainsString('KEY FEATURES', $vehicle->description);
        $this->assertStringContainsString('Intro text about the car.', $vehicle->description);
        $this->assertStringContainsString('DEALERSHIP BENEFITS', $vehicle->description);
        $this->assertStringContainsString('Call our sales team.', $vehicle->description);
    }

    public function testBulletModeHandlesBulletOnlyDescription()
    {
        $this->enableBulletMode();

        // Arona-style: the whole description is one single-newline bullet list
        $this->importWithDescription("• Radio\n • ABS\n • Cruise control\n • Alloy wheels");

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEquals(4, $vehicle->features()->count());
        $this->assertSame('', $vehicle->description);
    }

    public function testBulletModeIgnoresShortRuns()
    {
        $this->enableBulletMode();

        $this->importWithDescription("Great car\n- one prose dash line\nMore text about the car");

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEquals(0, $vehicle->features()->count());
        $this->assertStringContainsString('- one prose dash line', $vehicle->description);
    }

    public function testBulletModeUsesConfiguredMarkers()
    {
        $this->enableBulletMode(markers: '*');

        $this->importWithDescription("* Alloys\n* Bluetooth\n* Cruise control\n- Dash line\n- Another\n- Third");

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        // Only the * lines qualify; the - lines are not in the configured marker list
        $this->assertEqualsCanonicalizing(
            ['Alloys', 'Bluetooth', 'Cruise control'],
            $vehicle->features()->pluck('name')->toArray()
        );
        $this->assertStringContainsString('- Dash line', $vehicle->description);
    }

    public function testNoneModeSkipsExtractionEntirely()
    {
        Settings::make($this->featureSourceSetting('none'));

        $this->importWithDescription("• Radio\n • ABS\n • Cruise control\n • Alloy wheels");

        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEquals(0, $vehicle->features()->count());
        $this->assertStringContainsString('• Radio', $vehicle->description);
    }

    public function testBulletModeRemovesFeaturesDroppedFromTheFeed()
    {
        $this->enableBulletMode();

        Http::fake([
            'https://feeds.dealerhub.ie/api/v1/stock?*' => Http::sequence()
                ->push($this->responsePayload("• Alloys\n• Bluetooth\n• Cruise control"))
                ->push($this->responsePayload("• Alloys\n• Cruise control\n• Climate control")),
            '*' => Http::response([], 400),
        ]);

        new Skupenet()->runScheduledImport();
        $vehicle = Vehicle::query()->where('uuid', 900)->first();
        $this->assertEquals(3, $vehicle->features()->count());

        // Dealer removes Bluetooth in DealerHub; re-import must drop it here as well
        new Skupenet()->runScheduledImport();
        $this->assertEqualsCanonicalizing(
            ['Alloys', 'Cruise control', 'Climate control'],
            $vehicle->fresh()->features()->pluck('name')->toArray()
        );
    }

    private function enableBulletMode(?string $markers = null): void
    {
        Settings::make($this->featureSourceSetting('description-bullets'));

        if ($markers !== null) {
            Settings::make([
                'tab' => 'foo',
                'section' => 'foo',
                'group' => 'foo',
                'name' => 'foo',
                'config_key' => 'stock-skupenet-feature-markers',
                'value' => $markers,
                'type' => 'string'
            ]);
        }
    }

    private function featureSourceSetting(string $value): array
    {
        return [
            'tab' => 'foo',
            'section' => 'foo',
            'group' => 'foo',
            'name' => 'foo',
            'config_key' => 'stock-skupenet-feature-source',
            'value' => $value,
            'type' => 'string'
        ];
    }

    private function importWithDescription(string $description): void
    {
        Http::fake([
            'https://feeds.dealerhub.ie/api/v1/stock?*' => Http::response(
                $this->responsePayload($description)
            ),
            '*' => Http::response([], 400),
        ]);

        new Skupenet()->runScheduledImport();
    }

    private function responsePayload(string $description): array
    {
        return [
            'stock' => [
                [
                    'id' => 900,
                    'dhfDealerId' => 123,
                    'price' => 10000,
                    'currency' => 'GBP',
                    'stockType' => 'CARS',
                    'description' => $description,
                    'attributes' => [
                        'registration' => '212D1122',
                        'make' => 'Volkswagen',
                        'model' => 'Polo',
                        'bodyType' => 'Hatchback',
                    ],
                ],
            ],
            'paging' => ['totalPages' => 1],
        ];
    }
}
