<?php

namespace Tests\Tenant;

use App\ExportMapRepository;
use App\Models\ExportMap;
use App\ScheduledTasks\Actions\RunExportMapAction;
use App\ScheduledTasks\TaskRunContext;
use Mockery;
use Mtc\MercuryDataModels\ScheduledTaskRun;
use Tests\TenantTestCase;

class RunExportMapActionTest extends TenantTestCase
{
    public function testRunsTheExportMapThroughTheRepository(): void
    {
        $exportMap = ExportMap::factory()->create(['schedule_enabled' => false]);

        $repository = Mockery::mock(ExportMapRepository::class);
        $repository->shouldReceive('run')
            ->once()
            ->with(Mockery::on(fn ($map) => $map->id === $exportMap->id));
        $this->app->instance(ExportMapRepository::class, $repository);

        $result = app(RunExportMapAction::class)->execute(
            ['export_map_id' => $exportMap->id],
            new TaskRunContext(ScheduledTaskRun::factory()->create())
        );

        $this->assertEquals('completed', $result->status);
        $this->assertEquals($exportMap->id, $result->stats['export_map_id']);
    }

    public function testRefusesAMapOwnedByTheLegacyScheduler(): void
    {
        $exportMap = ExportMap::factory()->create(['schedule_enabled' => true]);

        $repository = Mockery::mock(ExportMapRepository::class);
        $repository->shouldNotReceive('run');
        $this->app->instance(ExportMapRepository::class, $repository);

        $result = app(RunExportMapAction::class)->execute(
            ['export_map_id' => $exportMap->id],
            new TaskRunContext(ScheduledTaskRun::factory()->create())
        );

        $this->assertEquals('failed', $result->status);
        $this->assertStringContainsString('legacy export-map scheduler', $result->message);
    }

    public function testFailsCleanlyWhenTheMapNoLongerExists(): void
    {
        $result = app(RunExportMapAction::class)->execute(
            ['export_map_id' => 999999],
            new TaskRunContext(ScheduledTaskRun::factory()->create())
        );

        $this->assertEquals('failed', $result->status);
        $this->assertStringContainsString('no longer exists', $result->message);
    }
}
