<?php

namespace Tests\Tenant;

use App\Console\Commands\DeleteNonAutoTraderVehicleImages;
use App\Facades\Settings;
use Mtc\MercuryDataModels\Media;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\Vehicle;
use Tests\TenantTestCase;

class DeleteNonAutoTraderVehicleImagesTest extends TenantTestCase
{
    private function setAutoTraderStockImport(bool $enabled): void
    {
        Settings::make([
            'tab' => 'foo',
            'section' => 'foo',
            'group' => 'foo',
            'name' => 'foo',
            'config_key' => 'stock-auto-trader-enabled',
            'value' => $enabled,
            'type' => 'boolean',
        ]);
    }

    private function attachMediaToVehicle(Vehicle $vehicle, ?string $imageProvider)
    {
        $media = Media::factory()->create(['image_provider' => $imageProvider]);

        return MediaUse::factory()->create([
            'media_id' => $media->id,
            'owner_type' => 'vehicle',
            'owner_id' => $vehicle->id,
            'primary' => false,
        ]);
    }

    public function testDeletesNonAutoTraderVehicleImages()
    {
        $this->setAutoTraderStockImport(true);

        $vehicle = Vehicle::factory()->create();
        $otherProviderUse = $this->attachMediaToVehicle($vehicle, 'skupenet');
        $noProviderUse = $this->attachMediaToVehicle($vehicle, null);

        $this->artisan(DeleteNonAutoTraderVehicleImages::class)->assertOk();

        $this->assertFalse(MediaUse::query()->where('id', $otherProviderUse->id)->exists());
        $this->assertFalse(Media::query()->where('id', $otherProviderUse->media_id)->exists());
        $this->assertFalse(MediaUse::query()->where('id', $noProviderUse->id)->exists());
        $this->assertFalse(Media::query()->where('id', $noProviderUse->media_id)->exists());
    }

    public function testRetainsAutoTraderVehicleImages()
    {
        $this->setAutoTraderStockImport(true);

        $vehicle = Vehicle::factory()->create();
        $autoTraderUse = $this->attachMediaToVehicle($vehicle, 'auto-trader');

        $this->artisan(DeleteNonAutoTraderVehicleImages::class)->assertOk();

        $this->assertTrue(MediaUse::query()->where('id', $autoTraderUse->id)->exists());
        $this->assertTrue(Media::query()->where('id', $autoTraderUse->media_id)->exists());
    }

    public function testDoesNotRunWhenAutoTraderStockImportDisabled()
    {
        $this->setAutoTraderStockImport(false);

        $vehicle = Vehicle::factory()->create();
        $otherProviderUse = $this->attachMediaToVehicle($vehicle, 'skupenet');

        $this->artisan(DeleteNonAutoTraderVehicleImages::class)->assertOk();

        $this->assertTrue(MediaUse::query()->where('id', $otherProviderUse->id)->exists());
        $this->assertTrue(Media::query()->where('id', $otherProviderUse->media_id)->exists());
    }
}
