<?php

namespace Tests\Tenant;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAttribute;
use Mtc\MercuryDataModels\VehicleAttributeValue;
use Tests\TenantTestCase;

class VehicleGetCustomTest extends TenantTestCase
{
    private function createCustomAttribute(Vehicle $vehicle, string $slug, int $count, array $values): void
    {
        $attribute = VehicleAttribute::factory()->create([
            'name' => $slug,
            'slug' => $slug,
            'type' => 'string',
            'count' => $count,
        ]);

        foreach (array_values($values) as $index => $value) {
            VehicleAttributeValue::factory()->create([
                'attribute_id' => $attribute->id,
                'owner_type' => 'vehicle',
                'owner_id' => $vehicle->id,
                'slug' => $slug,
                'type' => 'string',
                'value' => $value,
                'index' => $index,
            ]);
        }
    }

    public function testReturnsSingleValueWhenAttributeCountIsOne(): void
    {
        $vehicle = Vehicle::factory()->create();
        $this->createCustomAttribute($vehicle, 'finance_option', 1, ['4']);

        $this->assertSame('4', $vehicle->fresh()->getCustom('finance_option'));
    }

    public function testReturnsCollectionWhenAttributeCountIsGreaterThanOne(): void
    {
        $vehicle = Vehicle::factory()->create();
        $this->createCustomAttribute($vehicle, 'features', 2, ['alloys', 'bluetooth']);

        $result = $vehicle->fresh()->getCustom('features');

        $this->assertInstanceOf(Collection::class, $result);
        $this->assertEquals(['alloys', 'bluetooth'], $result->all());
    }

    public function testReturnsNullWhenAttributeIsMissing(): void
    {
        $vehicle = Vehicle::factory()->create();

        $this->assertNull($vehicle->fresh()->getCustom('does_not_exist'));
    }

    public function testUsesEagerLoadedRelationshipsWithoutExtraQueries(): void
    {
        $vehicle = Vehicle::factory()->create();
        $this->createCustomAttribute($vehicle, 'finance_option', 1, ['4']);

        // Load exactly as RunQuoteRequest does.
        DB::connection()->enableQueryLog();
        $loaded = Vehicle::query()
            ->with('attributeValues.attribute')
            ->findOrFail($vehicle->id);
        DB::connection()->flushQueryLog();

        $result = $loaded->getCustom('finance_option');

        $this->assertSame('4', $result);
        $this->assertCount(
            0,
            DB::connection()->getQueryLog(),
            'getCustom() must read from eager-loaded relations and run no further queries.'
        );
    }
}
