<?php

use App\Filament\Resources\BackupScheduleResource\Pages\ListBackupSchedules;
use App\Models\BackupSchedule;
use Filament\Facades\Filament;
use Livewire\Livewire;

test('owner can bulk delete backup schedules', function () {
    [$user, $tenant] = createUserWithTenant(role: 'owner');

    $scheduleA = BackupSchedule::query()->create([
        'tenant_id' => $tenant->id,
        'name' => 'Delete A',
        '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,
    ]);

    $scheduleB = BackupSchedule::query()->create([
        'tenant_id' => $tenant->id,
        'name' => 'Delete B',
        '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,
    ]);

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

    Livewire::test(ListBackupSchedules::class)
        ->callTableBulkAction('bulk_delete', collect([$scheduleA, $scheduleB]))
        ->assertHasNoTableBulkActionErrors();

    expect(BackupSchedule::query()->where('tenant_id', $tenant->id)->count())
        ->toBe(0);
});

test('operator cannot bulk delete backup schedules', function () {
    [$user, $tenant] = createUserWithTenant(role: 'operator');

    $scheduleA = BackupSchedule::query()->create([
        'tenant_id' => $tenant->id,
        'name' => 'Keep A',
        '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,
    ]);

    $scheduleB = BackupSchedule::query()->create([
        'tenant_id' => $tenant->id,
        'name' => 'Keep B',
        '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,
    ]);

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

    try {
        Livewire::test(ListBackupSchedules::class)
            ->callTableBulkAction('bulk_delete', collect([$scheduleA, $scheduleB]));
    } catch (\Throwable) {
        // Action should be hidden/blocked for operator users.
    }

    expect(BackupSchedule::query()->where('tenant_id', $tenant->id)->count())
        ->toBe(2);
});
