<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use Database\Seeders\Tenant\CapIdLocalCacheSettingSeeder;
use Mtc\MercuryDataModels\CapIdCache;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleMake;
use Mtc\MercuryDataModels\VehicleModel;
use Tests\TenantTestCase;

class CapIdCacheModelBackfillTest extends TenantTestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        $this->seed(CapIdLocalCacheSettingSeeder::class);
        Settings::update('cap-id-lookup-local-cache-enabled', true);
    }

    public function testSavingCacheRowWithMatchedModelBackfillsSiblingVehicle(): void
    {
        $make = VehicleMake::factory()->create();
        $model = VehicleModel::factory()->create(['make_id' => $make->id]);

        $vehicle = Vehicle::factory()->create([
            'cap_id' => '106927',
            'model_id' => null,
            'derivative' => '1.5 eTSI V2 5dr DSG',
        ]);

        // Creating a cache row that resolves this cap_id to a model should fire the
        // observer and backfill the vehicle that had no model_id.
        CapIdCache::create([
            'derivative' => '1.5 eTSI V2 5dr DSG',
            'cap_id' => '106927',
            'cap_matched_make_id' => $make->id,
            'cap_matched_model_id' => $model->id,
        ]);

        $this->assertEquals($model->id, $vehicle->fresh()->model_id);
    }

    public function testUpdatingCacheRowToAddMatchedModelBackfillsSiblingVehicle(): void
    {
        $make = VehicleMake::factory()->create();
        $model = VehicleModel::factory()->create(['make_id' => $make->id]);

        // Cache row exists but has no matched model yet -> no backfill on create.
        $cache = CapIdCache::create([
            'derivative' => '2.0 TDI 5dr',
            'cap_id' => '200001',
            'cap_matched_model_id' => null,
        ]);

        $vehicle = Vehicle::factory()->create([
            'cap_id' => '200001',
            'model_id' => null,
            'derivative' => '2.0 TDI 5dr',
        ]);

        $this->assertNull($vehicle->fresh()->model_id);

        $cache->update(['cap_matched_model_id' => $model->id]);

        $this->assertEquals($model->id, $vehicle->fresh()->model_id);
    }

    public function testExistingModelIdIsNotOverwritten(): void
    {
        $make = VehicleMake::factory()->create();
        $matchedModel = VehicleModel::factory()->create(['make_id' => $make->id]);
        $existingModel = VehicleModel::factory()->create(['make_id' => $make->id]);

        $vehicle = Vehicle::factory()->create([
            'cap_id' => '300001',
            'model_id' => $existingModel->id,
            'derivative' => '1.0 T 3dr',
        ]);

        CapIdCache::create([
            'derivative' => '1.0 T 3dr',
            'cap_id' => '300001',
            'cap_matched_model_id' => $matchedModel->id,
        ]);

        $this->assertEquals($existingModel->id, $vehicle->fresh()->model_id);
    }
}
