<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Http\Resources\VehicleListResource;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleAutoTraderData;
use Tests\TenantTestCase;

class VehicleListResourceTest extends TenantTestCase
{
    public function testListIncludesAutotraderMetricsWhenEnabled(): void
    {
        Settings::update('sales-channels-auto-trader-enabled', true);

        $vehicle = Vehicle::factory()->create();
        VehicleAutoTraderData::factory()->create([
            'vehicle_id' => $vehicle->id,
            'performance_rating' => 'ABOVE AVERAGE',
            'lead_count_rating' => 'HIGH',
            'ad_views' => 5,
            'ad_views_7d' => 23,
        ]);

        $resource = new VehicleListResource(Vehicle::query()->paginate(15))
            ->toArray(request());

        $meta = $resource['data'][0]['metaItems'];
        $this->assertEquals('ABOVE AVERAGE', $meta['at_performance_rating']);
        $this->assertEquals('HIGH', $meta['at_lead_count_rating']);
        $this->assertEquals(5, $meta['at_ad_views']);
        $this->assertEquals(23, $meta['at_ad_views_7d']);

        $columnIds = collect($resource['view_columns'])->pluck('id');
        $this->assertTrue($columnIds->contains('at_performance_rating'));
        $this->assertTrue($columnIds->contains('at_lead_count_rating'));
        $this->assertTrue($columnIds->contains('at_ad_views'));
        $this->assertTrue($columnIds->contains('at_ad_views_7d'));
    }

    public function testListOmitsAutotraderMetricsWhenDisabled(): void
    {
        Settings::update('sales-channels-auto-trader-enabled', false);

        Vehicle::factory()->create();

        $resource = new VehicleListResource(Vehicle::query()->paginate(15))
            ->toArray(request());

        $meta = $resource['data'][0]['metaItems'];
        $this->assertArrayNotHasKey('at_performance_rating', $meta);
        $this->assertArrayNotHasKey('at_lead_count_rating', $meta);
        $this->assertArrayNotHasKey('at_ad_views', $meta);
        $this->assertArrayNotHasKey('at_ad_views_7d', $meta);

        $columnIds = collect($resource['view_columns'])->pluck('id');
        $this->assertFalse($columnIds->contains('at_performance_rating'));
    }
}
