<?php

use App\Filament\Resources\BackupScheduleResource\Pages\ListBackupSchedules;
use App\Filament\Resources\EntraGroupResource\Pages\ListEntraGroups;
use App\Filament\Resources\InventoryItemResource\Pages\ListInventoryItems;
use App\Jobs\EntraGroupSyncJob;
use App\Jobs\RunBackupScheduleJob;
use App\Models\BackupSchedule;
use App\Models\OperationRun;
use App\Models\ManagedEnvironment;
use App\Services\Inventory\InventorySyncService;
use Filament\Facades\Filament;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);

it('rejects cross-tenant run starts (403) with no run records created', function () {
    Queue::fake();

    [$user, $tenantA] = createUserWithTenant(role: 'owner');
    $tenantB = ManagedEnvironment::factory()->create();

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

    $sync = app(InventorySyncService::class);
    $allTypes = $sync->defaultSelectionPayload()['policy_types'];

    Livewire::test(ListInventoryItems::class)
        ->callAction('run_inventory_sync', data: ['managed_environment_id' => $tenantB->getKey(), 'policy_types' => $allTypes])
        ->assertSuccessful();

    Queue::assertNothingPushed();

    expect(OperationRun::query()->where('managed_environment_id', $tenantB->id)->where('type', 'inventory_sync')->exists())->toBeFalse();
    expect(OperationRun::query()->where('managed_environment_id', $tenantB->id)->exists())->toBeFalse();
});

it('prevents run creation when a readonly member tries to start inventory sync', function () {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'readonly');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $sync = app(InventorySyncService::class);
    $allTypes = $sync->defaultSelectionPayload()['policy_types'];

    Livewire::test(ListInventoryItems::class)
        ->assertActionVisible('run_inventory_sync')
        ->assertActionDisabled('run_inventory_sync')
        ->callAction('run_inventory_sync', data: ['managed_environment_id' => $tenant->getKey(), 'policy_types' => $allTypes]);

    Queue::assertNothingPushed();
    expect(OperationRun::query()->where('managed_environment_id', $tenant->id)->where('type', 'inventory_sync')->exists())->toBeFalse();
    expect(OperationRun::query()->where('managed_environment_id', $tenant->id)->exists())->toBeFalse();
});

it('prevents run creation when a readonly member tries to start directory group sync', function () {
    Queue::fake();

    [$user, $tenant] = createUserWithTenant(role: 'readonly');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    Livewire::test(ListEntraGroups::class)
        ->assertActionVisible('sync_groups')
        ->assertActionDisabled('sync_groups')
        ->callAction('sync_groups');

    Queue::assertNotPushed(EntraGroupSyncJob::class);
    expect(OperationRun::query()->where('managed_environment_id', $tenant->id)->exists())->toBeFalse();
});

it('prevents run creation when a readonly member tries to run a backup schedule now', function () {
    Queue::fake([RunBackupScheduleJob::class]);

    [$user, $tenant] = createUserWithTenant(role: 'readonly');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $schedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Nightly',
        '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,
    ]);

    Livewire::test(ListBackupSchedules::class)
        ->assertTableActionVisible('runNow', $schedule)
        ->assertTableActionDisabled('runNow', $schedule)
        ->callTableAction('runNow', $schedule);

    Queue::assertNothingPushed();
    expect(OperationRun::query()->where('managed_environment_id', $tenant->id)->exists())->toBeFalse();
});

it('prevents run creation when a readonly member tries to retry a backup schedule', function () {
    Queue::fake([RunBackupScheduleJob::class]);

    [$user, $tenant] = createUserWithTenant(role: 'readonly');
    $this->actingAs($user);
    Filament::setTenant($tenant, true);

    $schedule = BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Nightly',
        '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,
    ]);

    Livewire::test(ListBackupSchedules::class)
        ->assertTableActionVisible('retry', $schedule)
        ->assertTableActionDisabled('retry', $schedule)
        ->callTableAction('retry', $schedule);

    Queue::assertNothingPushed();
    expect(OperationRun::query()->where('managed_environment_id', $tenant->id)->exists())->toBeFalse();
});
