<?php

namespace Tests\Feature;

use App\Facades\Settings;
use App\Jobs\BulkImportJob;
use App\Models\BulkImportLog;
use Database\Seeders\Global\CountrySeeder;
use Database\Seeders\Tenant\FinanceProductRestrictionSetting;
use Database\Seeders\Tenant\FinanceSettingSeeder;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\Finance\Jobs\FetchVehicleFinanceData;
use Mtc\MercuryDataModels\Vehicle;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

class VehicleControllerTest extends DatabaseTestCase
{
    use UserForTenant;

    public function testUpdate()
    {
        $this->seed(CountrySeeder::class);
        $vehicle = Vehicle::factory()->create(['slug' => null]);
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.vehicles.update', $vehicle), [
                'title' => 'lorem ipsum',
                'derivative' => 'foo baz bar',
                'registration_number' => 'AB12 DEV',
                'make_id' => 6,
                'is_published' => true,
                'model_id' => 7,
                'dealership_id' => 8,
                'transmission_id' => 9,
                'fuel_type_id' => 10,
                'drivetrain_id' => 11,
                'colour' => 'blue',
                'price' => 8900,
                'monthly_price' => 120,
                'deposit' => 3000,
                'door_count' => 4,
                'seats' => 5,
                'primary_media' => null,
                'manufacture_year' => 2020,
                'odometer_mi' => 100000,
                'engine_size_cc' => 1990,
                'co2' => 112,
                'mpg' => 44.4,
                'previous_owner_count' => 2,
                'first_registration_date' => '2020-01-03',
                'finance_examples' => [
                    [
                        'id' => 'abc-123',
                        'term' => 60,
                        'number_of_payments' => 40,
                        'finance_type' => 'HP',
                        'monthly_price' => 1400,
                        'apr' => 8.9,
                        'deposit' => 7000,
                    ]
                ]
            ]);

        $response->assertStatus(200);

        $vehicle->refresh();
        $this->assertNotNull($vehicle->slug);
        $this->assertEquals('lorem ipsum', $vehicle->title);
        $this->assertEquals('foo baz bar', $vehicle->derivative);
        $this->assertEquals('AB12 DEV', $vehicle->registration_number);
        $this->assertEquals(6, $vehicle->make_id);
        $this->assertEquals(7, $vehicle->model_id);
        $this->assertEquals(8, $vehicle->dealership_id);
        $this->assertEquals(9, $vehicle->transmission_id);
        $this->assertEquals(10, $vehicle->fuel_type_id);
        $this->assertEquals(11, $vehicle->drivetrain_id);
        $this->assertEquals('blue', $vehicle->colour);
        $this->assertEquals(8900, $vehicle->price);
        $this->assertEquals(120, $vehicle->monthly_price);
        $this->assertEquals(3000, $vehicle->deposit);
        $this->assertEquals(4, $vehicle->door_count);
        $this->assertEquals(5, $vehicle->seats);
        $this->assertEquals(2020, $vehicle->manufacture_year);
        $this->assertEquals(100000, $vehicle->odometer_mi);
        $this->assertEquals(1990, $vehicle->engine_size_cc);
        $this->assertEquals(112, $vehicle->co2);
        $this->assertEquals(44.4, $vehicle->mpg);
        $this->assertEquals(2, $vehicle->previous_owner_count);
        $this->assertEquals('2020-01-03', $vehicle->first_registration_date->format('Y-m-d'));
    }

    public function testUpdateDiferentRegNumberFormats()
    {
        $this->seed(CountrySeeder::class);
        $vehicle = Vehicle::factory()->create();
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.vehicles.update', $vehicle), [
                'title' => 'lorem ipsum',
                'derivative' => 'foo baz bar',
                'registration_number' => 'ab12 csw',
                'is_published' => true,
                'primary_media' => null,
                'make_id' => 6,
                'model_id' => 7,
                'dealership_id' => 8,
                'transmission_id' => 9,
                'fuel_type_id' => 10,
                'drivetrain_id' => 11,
                'colour' => 'blue',
                'price' => 8900,
                'monthly_price' => 120,
                'deposit' => 3000,
                'door_count' => 4,
                'seats' => 5,
                'manufacture_year' => 2020,
                'odometer_mi' => 100000,
                'engine_size_cc' => 1990,
                'co2' => 112,
                'mpg' => 44.4,
                'previous_owner_count' => 2,
                'first_registration_date' => '2020-01-03',
            ]);

        $vehicle->refresh();
        $this->assertEquals('AB12 CSW', $vehicle->registration_number);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->putJson(route('tenant.vehicles.update', $vehicle), [
                'title' => 'lorem ipsum',
                'derivative' => 'foo baz bar',
                'registration_number' => 'NW34LIO',
                'is_published' => true,
                'primary_media' => null,
                'make_id' => 6,
                'model_id' => 7,
                'dealership_id' => 8,
                'transmission_id' => 9,
                'fuel_type_id' => 10,
                'drivetrain_id' => 11,
                'colour' => 'blue',
                'price' => 8900,
                'monthly_price' => 120,
                'deposit' => 3000,
                'door_count' => 4,
                'seats' => 5,
                'manufacture_year' => 2020,
                'odometer_mi' => 100000,
                'engine_size_cc' => 1990,
                'co2' => 112,
                'mpg' => 44.4,
                'previous_owner_count' => 2,
                'first_registration_date' => '2020-01-03',
            ]);

        $response->assertStatus(200);

        $vehicle->refresh();
        $this->assertEquals('NW34 LIO', $vehicle->registration_number);
    }

    public function testGetImages()
    {
        $vehicle = Vehicle::factory()->create();
        Queue::fake();

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.vehicles.get-images', $vehicle));

        $response->assertStatus(200);
        Queue::assertNothingPushed();
    }

    public function testGetFinanceReturns422WhenStopFinanceSyncIsTrue()
    {
        Bus::fake();

        $this->seed(FinanceSettingSeeder::class);
        $this->seed(FinanceProductRestrictionSetting::class);
        Settings::update('finance-codeweavers-enabled', true);
        Settings::update('finance-codeweavers-api_key', 'test-key');
        Settings::update('finance-codeweavers-username', 'test-user');
        Settings::update('finance-codeweavers-password', 'test-pass');

        $vehicle = Vehicle::factory()->create([
            'price' => 10000,
            'cap_id' => '12345',
            'data' => ['stop_finance_sync' => true],
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.vehicles.get-finance', $vehicle));

        $response->assertStatus(422);
        Bus::assertNotDispatched(FetchVehicleFinanceData::class);
    }

    public function testVehicleImport()
    {
        Queue::fake();
        Storage::fake('file-storage');
        Storage::disk('file-storage')->put('foo/faz.xlsx', File::get(dirname(__DIR__) . '/data/vehicle-import.xlsx'));

        $log = BulkImportLog::query()
            ->create([
                'user_id' => 1,
                'object_type' => 'vehicle',
                'import_type' => 'default',
                'automations' => [],
                'filename' => 'foo/faz.xlsx',
            ]);

        new BulkImportJob('vehicle', 'foo/faz.xlsx', 'edit-vehicles', 'default')
            ->setLog($log)
            ->setAdditionalTasks([])
            ->handle();
        $this->assertEquals(3, Vehicle::query()->count());
    }
}
