<?php

use App\Filament\Resources\BackupScheduleResource;
use App\Filament\Resources\BackupScheduleResource\Pages\ListBackupSchedules;
use App\Models\BackupSchedule;
use App\Models\ManagedEnvironment;
use App\Support\Auth\UiTooltips;
use Filament\Actions\Action;
use Filament\Facades\Filament;
use Filament\Tables\Filters\TrashedFilter;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

function getBackupScheduleEmptyStateAction(Testable $component, string $name): ?Action
{
    foreach ($component->instance()->getTable()->getEmptyStateActions() as $action) {
        if ($action instanceof Action && $action->getName() === $name) {
            return $action;
        }
    }

    return null;
}

it('returns 404 for non-members trying to access schedule lifecycle pages', function () {
    $tenant = ManagedEnvironment::factory()->create();
    [$user] = createUserWithTenant(role: 'owner');

    $this->actingAs($user)
        ->get(BackupScheduleResource::getUrl('index', tenant: $tenant))
        ->assertNotFound();
});

it('treats members without manage capability as forbidden for archive and restore', function () {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $schedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Lifecycle auth readonly',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    Livewire::test(ListBackupSchedules::class)
        ->assertTableActionDisabled('archive', $schedule)
        ->assertTableActionExists('archive', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), $schedule)
        ->callTableAction('archive', $schedule);

    expect(function () use ($user, $schedule): void {
        Gate::forUser($user)->authorize('delete', $schedule);
    })->toThrow(AuthorizationException::class);

    $schedule->delete();

    Livewire::test(ListBackupSchedules::class)
        ->filterTable(TrashedFilter::class, false)
        ->assertTableActionDisabled('restore', BackupSchedule::withTrashed()->findOrFail($schedule->id))
        ->assertTableActionExists('restore', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), BackupSchedule::withTrashed()->findOrFail($schedule->id));

    expect(function () use ($user, $schedule): void {
        Gate::forUser($user)->authorize('restore', $schedule->fresh());
    })->toThrow(AuthorizationException::class);
});

it('requires confirmation for destructive backup schedule lifecycle actions', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $activeSchedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Lifecycle confirmation active',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);

    $archivedSchedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Lifecycle confirmation archived',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '02:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);
    $archivedSchedule->delete();

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    Livewire::test(ListBackupSchedules::class)
        ->assertTableActionExists('archive', fn (Action $action): bool => $action->isConfirmationRequired(), $activeSchedule);

    Livewire::test(ListBackupSchedules::class)
        ->filterTable(TrashedFilter::class, false)
        ->assertTableActionExists('forceDelete', fn (Action $action): bool => $action->isConfirmationRequired(), BackupSchedule::withTrashed()->findOrFail($archivedSchedule->id));
});

it('disables backup schedule create in the empty state for members without manage capability', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'readonly');

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $component = Livewire::test(ListBackupSchedules::class)
        ->assertTableEmptyStateActionsExistInOrder(['create']);

    $action = getBackupScheduleEmptyStateAction($component, 'create');

    expect($action)->not->toBeNull();
    expect($action?->isDisabled())->toBeTrue();
    expect($action?->getTooltip())->toBe('You do not have permission to create backup schedules.');
});

it('treats members without tenant delete capability as forbidden for force delete', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

    $schedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Force delete forbidden',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);
    $schedule->delete();

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    Livewire::test(ListBackupSchedules::class)
        ->filterTable(TrashedFilter::class, false)
        ->assertTableActionDisabled('forceDelete', BackupSchedule::withTrashed()->findOrFail($schedule->id))
        ->assertTableActionExists('forceDelete', fn (Action $action): bool => $action->getTooltip() === UiTooltips::insufficientPermission(), BackupSchedule::withTrashed()->findOrFail($schedule->id));

    expect(function () use ($user, $schedule): void {
        Gate::forUser($user)->authorize('forceDelete', $schedule->fresh());
    })->toThrow(AuthorizationException::class);
});

it('returns 404 and mutates nothing when forged foreign-tenant schedule keys are mounted', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $foreignTenant = ManagedEnvironment::factory()->create();

    $activeForeignSchedule = BackupSchedule::query()->create([
        'managed_environment_id' => $foreignTenant->id,
        'name' => 'Foreign active schedule',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);

    $trashedForeignSchedule = BackupSchedule::query()->create([
        'managed_environment_id' => $foreignTenant->id,
        'name' => 'Foreign trashed schedule',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);
    $trashedForeignSchedule->delete();

    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $activeComponent = Livewire::test(ListBackupSchedules::class);

    expect(fn () => $activeComponent->instance()->mountTableAction('archive', (string) $activeForeignSchedule->getKey()))
        ->toThrow(NotFoundHttpException::class);

    $trashedComponent = Livewire::test(ListBackupSchedules::class)
        ->filterTable(TrashedFilter::class, false);

    expect(fn () => $trashedComponent->instance()->mountTableAction('restore', (string) $trashedForeignSchedule->getKey()))
        ->toThrow(NotFoundHttpException::class);

    expect(fn () => $trashedComponent->instance()->mountTableAction('forceDelete', (string) $trashedForeignSchedule->getKey()))
        ->toThrow(NotFoundHttpException::class);

    expect($activeForeignSchedule->fresh()?->trashed())->toBeFalse();
    expect(BackupSchedule::withTrashed()->find($trashedForeignSchedule->getKey()))->not->toBeNull();
});
