<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\VehicleSpec\Jobs\ApplyCapSectorBodyType;
use Database\Seeders\Tenant\VehicleSpecSeeder;
use Illuminate\Support\Facades\Queue;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;

class BackfillBodyTypeFromCapSectorCommandTest extends TenantTestCase
{
    private const COMMAND = 'cap:backfill-body-type-from-sector';

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed(VehicleSpecSeeder::class);

        Settings::update('vehicle-spec-providers-cap-subscriber_id', 12345);
        Settings::update('vehicle-spec-providers-cap-password', 'test_password');
    }

    public function testSkipsWhenCapIsDisabled(): void
    {
        Settings::update('vehicle-spec-providers-cap-enabled', false);
        Settings::update('vehicle-spec-providers-cap-use-sector-for-body-type', true);

        Queue::fake();

        $this->artisan(self::COMMAND)
            ->expectsOutputToContain('CAP is not enabled')
            ->assertSuccessful();

        Queue::assertNothingPushed();
    }

    public function testSkipsWhenSectorSettingIsDisabled(): void
    {
        Settings::update('vehicle-spec-providers-cap-enabled', true);
        Settings::update('vehicle-spec-providers-cap-use-sector-for-body-type', false);

        Queue::fake();

        $this->artisan(self::COMMAND)
            ->expectsOutputToContain('CAP sector body type override is not enabled')
            ->assertSuccessful();

        Queue::assertNothingPushed();
    }

    public function testDispatchesNoJobsWhenNoVehiclesHaveCapId(): void
    {
        Settings::update('vehicle-spec-providers-cap-enabled', true);
        Settings::update('vehicle-spec-providers-cap-use-sector-for-body-type', true);

        Vehicle::factory()->create(['cap_id' => null]);
        Vehicle::factory()->create(['cap_id' => '']);

        Queue::fake();

        $this->artisan(self::COMMAND)
            ->expectsOutputToContain('Queued 0 ApplyCapSectorBodyType jobs')
            ->assertSuccessful();

        Queue::assertNothingPushed();
    }

    public function testDispatchesOneJobPerVehicleWithCapId(): void
    {
        Settings::update('vehicle-spec-providers-cap-enabled', true);
        Settings::update('vehicle-spec-providers-cap-use-sector-for-body-type', true);

        Vehicle::factory()->create(['cap_id' => '101666']);
        Vehicle::factory()->create(['cap_id' => '101667']);
        Vehicle::factory()->create(['cap_id' => null]);
        Vehicle::factory()->create(['cap_id' => '']);

        Queue::fake();

        $this->artisan(self::COMMAND)
            ->expectsOutputToContain('Queued 2 ApplyCapSectorBodyType jobs on the specs queue.')
            ->assertSuccessful();

        Queue::assertPushed(ApplyCapSectorBodyType::class, 2);
        Queue::assertPushedOn('specs', ApplyCapSectorBodyType::class);
    }
}
