<?php

namespace Tests\Tenant;

use App\Facades\Settings;
use App\Jobs\VehiclesInVideoExportJob;
use App\Modules\SalesChannels\VehiclesInVideo;
use Database\Seeders\Tenant\VehiclesInVideoExportSeeder;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\SalesChannelHistory;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;

class VehiclesInVideoExportTest extends TenantTestCase
{
    public function testExportJobWritesFileAndLogsHistory(): void
    {
        Storage::fake('vehicles-in-video-export');
        $this->seed(VehiclesInVideoExportSeeder::class);
        Vehicle::factory(5)->create();
        Settings::update('sales-channels-vehicles-in-video-file-name', 'feed.csv');

        new VehiclesInVideoExportJob()->handle();

        Storage::disk('vehicles-in-video-export')->assertExists('feed.csv');
        $logged = SalesChannelHistory::query()
            ->where('channel', 'vehicles-in-video')
            ->where('was_successful', true)
            ->exists();
        $this->assertTrue($logged);
    }

    public function testExportIncludesUnpublishedVehicles(): void
    {
        Storage::fake('vehicles-in-video-export');
        $this->seed(VehiclesInVideoExportSeeder::class);
        Vehicle::factory()->create(['is_published' => true]);
        Vehicle::factory()->create(['is_published' => false]);

        $rows = new \App\Exports\VehiclesInVideoExport()->collection();

        $this->assertCount(2, $rows);
    }

    public function testRunScheduledExportDispatchesJobWhenEnabled(): void
    {
        $this->seed(VehiclesInVideoExportSeeder::class);
        Settings::update('sales-channels-vehicles-in-video-enabled', true);
        Queue::fake();

        app(VehiclesInVideo::class)->runScheduledExport();

        Queue::assertPushed(VehiclesInVideoExportJob::class);
    }

    public function testRunScheduledExportDoesNothingWhenDisabled(): void
    {
        $this->seed(VehiclesInVideoExportSeeder::class);
        Settings::update('sales-channels-vehicles-in-video-enabled', false);
        Queue::fake();

        app(VehiclesInVideo::class)->runScheduledExport();

        Queue::assertNothingPushed();
    }
}
