<?php

namespace Tests\Feature\Controllers;

use App\Models\ExportMap;
use Database\Seeders\Global\ScheduledTaskPermissionSeed;
use Mtc\MercuryDataModels\ScheduledTask;
use Mtc\MercuryDataModels\ScheduledTaskAction;
use Tests\DatabaseTestCase;
use Tests\UserForTenant;

class ExportMapCoexistenceTest extends DatabaseTestCase
{
    use UserForTenant;

    #[\Override]
    protected function setUp(): void
    {
        parent::setUp();
        $this->withHeader('X-Tenant', tenant('id'));
        $this->actingAs($this->getUser());
        (new ScheduledTaskPermissionSeed())->run();
        app(\Spatie\Permission\PermissionRegistrar::class)->forgetCachedPermissions();
    }

    public function testEnablingLegacyScheduleIsRejectedForTaskOwnedMaps(): void
    {
        $exportMap = ExportMap::factory()->create(['schedule_enabled' => false, 'type' => 'vehicle']);

        $task = ScheduledTask::factory()->create(['name' => 'Owning task']);
        ScheduledTaskAction::factory()->create([
            'scheduled_task_id' => $task->id,
            'action_type' => 'export-map',
            'config' => ['export_map_id' => $exportMap->id],
        ]);

        $response = $this->putJson("api/settings/export-maps/{$exportMap->id}", [
            'name' => $exportMap->name,
            'active' => true,
            'format' => 'csv',
            'columns' => ['title'],
            'ftp_export_enabled' => false,
            'include_header_row' => true,
            'api_url_enabled' => false,
            'schedule_enabled' => true,
            'schedule' => 'daily',
            'export_time' => '08:00',
        ]);

        $response->assertUnprocessable();
        $this->assertStringContainsString('Owning task', $response->json('errors.schedule_enabled.0'));
    }

    public function testLegacyScheduleStillWorksForUnownedMaps(): void
    {
        $exportMap = ExportMap::factory()->create(['schedule_enabled' => false, 'type' => 'vehicle']);

        $response = $this->putJson("api/settings/export-maps/{$exportMap->id}", [
            'name' => $exportMap->name,
            'active' => true,
            'format' => 'csv',
            'columns' => ['title'],
            'ftp_export_enabled' => false,
            'include_header_row' => true,
            'api_url_enabled' => false,
            'schedule_enabled' => true,
            'schedule' => 'daily',
            'export_time' => '08:00',
        ]);

        $response->assertOk();
        $this->assertTrue($exportMap->fresh()->schedule_enabled);
    }

    public function testTaskActionRejectsLegacyScheduledMapAtSave(): void
    {
        $legacyMap = ExportMap::factory()->create(['schedule_enabled' => true, 'type' => 'vehicle']);
        $task = ScheduledTask::factory()->create();

        $response = $this->putJson("api/settings/scheduled-tasks/{$task->id}", [
            'name' => $task->name,
            'trigger_type' => ScheduledTask::TRIGGER_SCHEDULE,
            'frequency' => 'daily',
            'run_times' => ['08:00'],
            'actions' => [
                ['action_type' => 'export-map', 'config' => ['export_map_id' => $legacyMap->id]],
            ],
        ]);

        $response->assertUnprocessable();
        $this->assertArrayHasKey('actions.0.config.export_map_id', $response->json('errors'));
    }
}
