<?php

namespace Tests\Tenant;

use App\Events\LoadDealershipDataFields;
use App\Services\DealershipAdditionalFieldsRegistry;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\VehicleAttribute;
use Mtc\MercuryDataModels\VehicleAttributeValue;
use Tests\TenantTestCase;

class DealershipAdditionalFieldsTest extends TenantTestCase
{
    private function registerFields(): void
    {
        Event::listen(LoadDealershipDataFields::class, fn () => [
            'silver-bullet-dealer-id' => ['type' => 'number', 'label' => 'Dealer ID'],
            'silver-bullet-disabled' => ['type' => 'checkbox', 'label' => 'Disabled'],
            'rapid-rtc-mailbox' => ['type' => 'text', 'label' => 'Mailbox'],
        ]);
    }

    public function testAdditionalFieldFallsBackToDataColumn(): void
    {
        $this->registerFields();
        $dealership = Dealership::factory()->create([
            'data' => ['rapid-rtc-mailbox' => 'legacy@example.com'],
        ]);

        $this->assertSame('legacy@example.com', $dealership->additionalField('rapid-rtc-mailbox'));
    }

    public function testAttributeValueTakesPrecedenceOverDataColumn(): void
    {
        $this->registerFields();
        $registry = $this->app->make(DealershipAdditionalFieldsRegistry::class);
        $dealership = Dealership::factory()->create([
            'data' => ['rapid-rtc-mailbox' => 'legacy@example.com'],
        ]);

        $registry->saveValue($dealership, 'rapid-rtc-mailbox', 'new@example.com');

        $dealership->refresh()->load('attributeValues');
        $this->assertSame('new@example.com', $dealership->additionalField('rapid-rtc-mailbox'));
    }

    public function testRegistrySavesNumberFieldToFloatColumn(): void
    {
        $this->registerFields();
        $registry = $this->app->make(DealershipAdditionalFieldsRegistry::class);
        $dealership = Dealership::factory()->create();

        $registry->saveValue($dealership, 'silver-bullet-dealer-id', '42');

        $attribute = VehicleAttribute::query()->where('model', 'dealership')
            ->where('slug', 'silver-bullet-dealer-id')->first();
        $this->assertNotNull($attribute);
        $value = VehicleAttributeValue::query()
            ->where('attribute_id', $attribute->id)
            ->where('owner_id', $dealership->id)
            ->where('owner_type', 'dealership')
            ->first();
        $this->assertNotNull($value);
        $this->assertSame(42.0, (float) $value->value_float);
        $this->assertSame(42.0, (float) $dealership->refresh()->additionalField('silver-bullet-dealer-id'));
    }

    public function testRegistrySavesCheckboxAsBooleanInteger(): void
    {
        $this->registerFields();
        $registry = $this->app->make(DealershipAdditionalFieldsRegistry::class);
        $dealership = Dealership::factory()->create();

        $registry->saveValue($dealership, 'silver-bullet-disabled', true);

        $this->assertTrue($dealership->refresh()->additionalField('silver-bullet-disabled'));
    }

    public function testMigrationCommandCopiesDataValuesIntoAttributeValues(): void
    {
        $this->registerFields();
        $dealership = Dealership::factory()->create([
            'data' => [
                'rapid-rtc-mailbox' => 'legacy@example.com',
                'silver-bullet-dealer-id' => 7,
                'unknown-field' => 'ignored',
            ],
        ]);

        $this->artisan('dealerships:migrate-data-to-attributes')->assertSuccessful();

        $dealership->refresh()->load('attributeValues');
        $this->assertSame('legacy@example.com', $dealership->additionalField('rapid-rtc-mailbox'));
        $this->assertSame(7.0, (float) $dealership->additionalField('silver-bullet-dealer-id'));
        $this->assertNull(VehicleAttribute::query()->where('slug', 'unknown-field')->first());
    }

    public function testMigrationCommandSkipsExistingAttributeValues(): void
    {
        $this->registerFields();
        $registry = $this->app->make(DealershipAdditionalFieldsRegistry::class);
        $dealership = Dealership::factory()->create([
            'data' => ['rapid-rtc-mailbox' => 'legacy@example.com'],
        ]);
        $registry->saveValue($dealership, 'rapid-rtc-mailbox', 'preserved@example.com');

        $this->artisan('dealerships:migrate-data-to-attributes')->assertSuccessful();

        $this->assertSame('preserved@example.com', $dealership->refresh()->additionalField('rapid-rtc-mailbox'));
    }
}
