<?php

use App\Filament\Resources\BackupScheduleResource\Pages\CreateBackupSchedule;
use App\Filament\Resources\BackupScheduleResource\Pages\EditBackupSchedule;
use App\Filament\Resources\BackupScheduleResource;
use App\Models\BackupSchedule;
use App\Models\ManagedEnvironment;
use Carbon\CarbonImmutable;
use Filament\Facades\Filament;
use Livewire\Livewire;

test('backup schedules listing is tenant scoped', function () {
    [$user, $tenantA] = createUserWithTenant(role: 'manager');
    $tenantB = ManagedEnvironment::factory()->create([
        'workspace_id' => $tenantA->workspace_id,
    ]);

    createUserWithTenant(tenant: $tenantB, user: $user, role: 'manager');

    BackupSchedule::query()->create([
        'managed_environment_id' => $tenantA->id,
        'name' => 'ManagedEnvironment A schedule',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '01:00:00',
        'days_of_week' => null,
        'policy_types' => [
            'deviceConfiguration',
            'groupPolicyConfiguration',
            'settingsCatalogPolicy',
        ],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);

    BackupSchedule::query()->create([
        'managed_environment_id' => $tenantB->id,
        'name' => 'ManagedEnvironment B schedule',
        'is_enabled' => true,
        'timezone' => 'UTC',
        'frequency' => 'daily',
        'time_of_day' => '02:00:00',
        'days_of_week' => null,
        'policy_types' => ['deviceCompliancePolicy'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
    ]);

    $this->actingAs($user);

    // createUserWithTenant() may be called multiple times in this test; ensure the current
    // workspace matches the tenant we are about to access.
    session()->put(\App\Support\Workspaces\WorkspaceContext::SESSION_KEY, (int) $tenantA->workspace_id);

    $this->get(BackupScheduleResource::getUrl('index', tenant: $tenantA))
        ->assertOk()
        ->assertSee('ManagedEnvironment A schedule')
        ->assertSee('Device Configuration')
        ->assertSee('more')
        ->assertDontSee('ManagedEnvironment B schedule');
});

test('backup schedules listing shows next run in schedule timezone', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

    BackupSchedule::query()->create([
        'managed_environment_id' => $tenant->id,
        'name' => 'Berlin schedule',
        'is_enabled' => true,
        'timezone' => 'Europe/Berlin',
        'frequency' => 'daily',
        'time_of_day' => '10:17:00',
        'days_of_week' => null,
        'policy_types' => ['deviceConfiguration'],
        'include_foundations' => true,
        'retention_keep_last' => 30,
        'next_run_at' => CarbonImmutable::create(2026, 1, 5, 9, 17, 0, 'UTC'),
    ]);

    $this->actingAs($user);

    $this->get(BackupScheduleResource::getUrl('index', tenant: $tenant))
        ->assertOk()
        ->assertSee('Jan 5, 2026 10:17:00');
});

test('backup schedules pages return 404 for unauthorized tenant', function () {
    [$user] = createUserWithTenant(role: 'manager');
    $unauthorizedTenant = ManagedEnvironment::factory()->create();

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

test('manager can create and edit backup schedules via filament', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

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

    Livewire::test(CreateBackupSchedule::class)
        ->fillForm([
            'name' => 'Daily at 10',
            'is_enabled' => true,
            'timezone' => 'UTC',
            'frequency' => 'daily',
            'time_of_day' => '10:00',
            'policy_types' => ['deviceConfiguration'],
            'include_foundations' => true,
            'retention_keep_last' => 30,
        ])
        ->call('create')
        ->assertHasNoFormErrors();

    $schedule = BackupSchedule::query()->where('managed_environment_id', $tenant->id)->first();
    expect($schedule)->not->toBeNull();
    expect($schedule->next_run_at)->not->toBeNull();

    Livewire::test(EditBackupSchedule::class, ['record' => $schedule->getRouteKey()])
        ->fillForm([
            'name' => 'Daily at 11',
        ])
        ->call('save')
        ->assertHasNoFormErrors();

    $schedule->refresh();
    expect($schedule->name)->toBe('Daily at 11');
});

test('soft-deleted schedules are excluded from default schedule queries', function () {
    [$user, $tenant] = createUserWithTenant(role: 'manager');

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

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

    $archived->delete();

    expect(BackupSchedule::query()->pluck('id')->all())
        ->toBe([(int) $active->getKey()]);

    expect(BackupSchedule::withTrashed()->pluck('id')->all())
        ->toContain((int) $active->getKey(), (int) $archived->getKey());

    $this->actingAs($user);

    $this->get(BackupScheduleResource::getUrl('index', tenant: $tenant))
        ->assertOk()
        ->assertSee('Active schedule')
        ->assertDontSee('Archived schedule');
});
