<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Jobs\ImportImagesFromUrlList;
use App\Modules\Stock\Skupenet;
use Carbon\Carbon;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleType;
use Tests\TenantTestCase;

class SkupenetTest extends TenantTestCase
{
    public function testImport()
    {
        Queue::fake();
        Http::fake([
            'https://feeds.dealerhub.ie/api/v1/stock?*' => Http::response($this->response()),
            "*" => Http::response([], 400),
        ]);
        Settings::make([
            'tab' => 'foo',
            'section' => 'foo',
            'group' => 'foo',
            'name' => 'foo',
            'config_key' => 'app-details-currency',
            'value' => 'GBP',
            'type' => 'string'
        ]);

        Settings::make([
            'tab' => 'foo',
            'section' => 'foo',
            'group' => 'foo',
            'name' => 'foo',
            'config_key' => 'stock-skupenet-sync-images',
            'value' => true,
            'type' => 'boolean'
        ]);

        Settings::make([
            'tab' => 'Automotive',
            'section' => 'DMS vehicle sync',
            'group' => 'General',
            'name' => 'Override registration year with model year',
            'config_key' => 'stock-override-reg-year-with-model-year',
            'type' => 'boolean',
            'value' => true,
        ]);

        Dealership::factory()->create(['data' => ['skupenet-location-id' => 123]]);
        new Skupenet()->runScheduledImport();

        Http::assertSent(fn (Request $request) => $request->url() === 'https://feeds.dealerhub.ie/api/v1/stock?dealerIds=123&pageSize=50&page=1');
        $this->assertEquals(4, Vehicle::query()->count());
        $this->assertTrue(Vehicle::query()->where('vrm_condensed', '212D1122')->exists());

        $this->assertEquals(
            VehicleType::CAR->value,
            Vehicle::where('uuid', 123)->first()->type
        );

        $this->assertEquals(
            VehicleType::LCV->value,
            Vehicle::where('uuid', 333)->first()->type
        );

        $this->assertEquals(
            VehicleType::MOTORCYCLE->value,
            Vehicle::where('uuid', 444)->first()->type
        );

        $v123 = Vehicle::where('uuid', 123)->first();
        $this->assertNotNull($v123);
        $this->assertEquals(250, (int) $v123->battery_range);
        $this->assertEquals(44, (int) $v123->battery_capacity_kwh);
        // reg date should be extracted from VRM
        $this->assertEquals('2021-07-01', $v123->first_registration_date->format('Y-m-d'));

        $v222 = Vehicle::where('uuid', 222)->first();
        $this->assertNotNull($v222);
        $this->assertNull($v222->battery_range);
        $this->assertNull($v222->battery_capacity_kwh);
        // reg date cannot be extracted from vrm and no manufacture year to guess from
        $this->assertNull($v222->first_registration_date);

        $v333 = Vehicle::where('uuid', 333)->first();
        // reg date should be guessed from manufacture year
        $this->assertEquals('2019-01-01', $v333->first_registration_date->format('Y-m-d'));

        $v444 = Vehicle::where('uuid', 444)->first();
        // reg date should be 2021 but model year is 2022.
        $this->assertEquals('2022-01-01', $v444->first_registration_date->format('Y-m-d'));

        Queue::assertPushed(ImportImagesFromUrlList::class);
    }

    public function testImportSetsStockArrivalDateFromFeedCreatedAt()
    {
        Queue::fake();
        Http::fake([
            'https://feeds.dealerhub.ie/api/v1/stock?*' => Http::response($this->response()),
            "*" => Http::response([], 400),
        ]);
        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]]);
        new Skupenet()->runScheduledImport();

        // vehicle 123 carries createdAt in the feed; stored date-only
        $v123 = Vehicle::query()->where('uuid', 123)->first();
        $this->assertNotNull($v123->stock_arrival_date);
        $this->assertEquals('2026-07-03', $v123->stock_arrival_date->format('Y-m-d'));

        // vehicle 222 has no createdAt in the feed, so nothing is set
        $this->assertNull(Vehicle::query()->where('uuid', 222)->first()->stock_arrival_date);

        // a manually corrected value survives a re-import
        $v123->update(['stock_arrival_date' => Carbon::parse('2020-01-01')]);
        new Skupenet()->runScheduledImport();
        $this->assertEquals('2020-01-01', $v123->fresh()->stock_arrival_date->format('Y-m-d'));
    }

    public function testInvalidRegDateFromVrm()
    {
        $skupenet = new Skupenet();

        // non-Irish and non-UK VRM format
        $this->assertNull($skupenet->getRegistrationDateFromRegistrationNumber('12345'));

        // valid UK format - first half of year (NN 01-49)
        $this->assertEquals('2023-03-01', $skupenet->getRegistrationDateFromRegistrationNumber('AB23XYZ'));
        $this->assertEquals('2002-03-01', $skupenet->getRegistrationDateFromRegistrationNumber('AB02ABC'));

        // valid UK format - second half of year (NN 51-99)
        $this->assertEquals('2023-09-01', $skupenet->getRegistrationDateFromRegistrationNumber('AB73XYZ'));
        $this->assertEquals('2002-09-01', $skupenet->getRegistrationDateFromRegistrationNumber('AB52ABC'));

        // lowercase UK format is still accepted
        $this->assertEquals('2023-03-01', $skupenet->getRegistrationDateFromRegistrationNumber('ab23xyz'));

        // malformed UK plates - a digit in the first two positions must be rejected
        $this->assertNull($skupenet->getRegistrationDateFromRegistrationNumber('X999ABC'));
        $this->assertNull($skupenet->getRegistrationDateFromRegistrationNumber('1A23XYZ'));

        // malformed UK plates - letters in the digit positions must be rejected
        $this->assertNull($skupenet->getRegistrationDateFromRegistrationNumber('ABCDXYZ'));

        // valid Irish format (3-digit prefix, post-2012)
        $this->assertEquals('2021-01-01', $skupenet->getRegistrationDateFromRegistrationNumber('211D3008'));
        $this->assertEquals('2022-07-01', $skupenet->getRegistrationDateFromRegistrationNumber('222G1234'));

        // Irish format starting with digits must not be caught by the UK regex
        $this->assertNotNull($skupenet->getRegistrationDateFromRegistrationNumber('221D0001'));

        // Northern Ireland format
        $this->assertNull($skupenet->getRegistrationDateFromRegistrationNumber('ABC1234'));
    }

    private function response(): array
    {
        return [
            'stock' => [
                [
                    'id' => 123,
                    'dhfDealerId' => 123,
                    'price' => 11223,
                    'currency' => 'GBP',
                    'stockType' => 'CARS',
                    'description' => 'lorem ipsum dolor sit amet',
                    'attributes' => [
                        'registration' => '212D1122',
                        'make' => 'Volkswagen',
                        'model' => 'ID.5',
                        'trim' => 'MAX',
                        'bodyType' => 'Sedan',
                        'batteryCapacityKwh' => 44.5,
                        'batteryRangeKm' => 250.4,

                    ],
                    'createdAt' => '2026-07-03T15:31:22.640093',
                    'images' => [
                        [
                            'url' => 'a.com/123',
                        ],
                        [
                            'url' => 'a.com/222',
                        ],
                    ],
                ],
                [
                    'id' => 222,
                    'dhfDealerId' => 123,
                    'price' => 13443,
                    'currency' => 'GBP',
                    'stockType' => 'CARS',
                    'description' => 'lorem ipsum dolor sit amet',
                    'attributes' => [
                        'registration' => '12345',
                        'make' => 'Ford',
                        'model' => 'Focus',
                        'bodyType' => 'Sedan',
                    ],
                ],
                [
                    'id' => 333,
                    'dhfDealerId' => 123,
                    'price' => 13443,
                    'currency' => 'GBP',
                    'stockType' => 'COMMERCIALS',
                    'description' => 'lorem ipsum dolor sit amet',
                    'attributes' => [
                        'registration' => '45678',
                        'make' => 'Ford',
                        'model' => 'Transit',
                        'bodyType' => 'Commercial/Van',
                        'year' => '2019',
                    ],
                ],
                [
                    'id' => 444,
                    'dhfDealerId' => 123,
                    'price' => 900,
                    'currency' => 'GBP',
                    'stockType' => 'bike',
                    'description' => 'test bike',
                    'attributes' => [
                        'registration' => 'AB71XYZ',
                        'make' => 'Yamaha',
                        'model' => 'MT-07',
                        'year' => '2022',
                    ],
                ],
            ],
            'paging' => [
                'totalPages' => 1,
            ],
        ];
    }
}
