<?php

declare(strict_types=1);

use App\Filament\Resources\ReviewPackResource;
use App\Filament\Resources\ReviewPackResource\Pages\ListReviewPacks;
use App\Models\ReviewPack;
use App\Models\Tenant;
use App\Services\ReviewPackService;
use App\Support\Auth\UiTooltips;
use App\Support\ReviewPackStatus;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    Storage::fake('exports');
});

// ─── Non-Member Access ───────────────────────────────────────

it('returns 404 for non-member on list page', function (): void {
    $targetTenant = Tenant::factory()->create();
    $otherTenant = Tenant::factory()->create();

    [$user] = createUserWithTenant($otherTenant, role: 'owner');

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

it('returns 404 for non-member on view page', function (): void {
    $targetTenant = Tenant::factory()->create();
    $otherTenant = Tenant::factory()->create();

    [$user] = createUserWithTenant($otherTenant, role: 'owner');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $targetTenant->getKey(),
    ]);

    $this->actingAs($user)
        ->get(ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $targetTenant))
        ->assertNotFound();
});

it('returns 404 for non-member on download route', function (): void {
    $targetTenant = Tenant::factory()->create();
    $otherTenant = Tenant::factory()->create();

    [$user] = createUserWithTenant($otherTenant, role: 'owner');

    $filePath = 'review-packs/rbac-test.zip';
    Storage::disk('exports')->put($filePath, 'PK-fake');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $targetTenant->getKey(),
        'file_path' => $filePath,
        'file_disk' => 'exports',
    ]);

    // Note: download route uses signed middleware, not tenant-scoped RBAC.
    // Any user with a valid signature can download. This is by design.
    $signedUrl = app(ReviewPackService::class)->generateDownloadUrl($pack);

    $this->actingAs($user)->get($signedUrl)->assertOk();
});

// ─── REVIEW_PACK_VIEW Member ────────────────────────────────

it('allows readonly member to access list page', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

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

it('allows readonly member to access view page', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'initiated_by_user_id' => (int) $user->getKey(),
    ]);

    $this->actingAs($user)
        ->get(ReviewPackResource::getUrl('view', ['record' => $pack], tenant: $tenant))
        ->assertOk();
});

it('allows readonly member to download via signed URL', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    $filePath = 'review-packs/readonly-test.zip';
    Storage::disk('exports')->put($filePath, 'PK-fake');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'initiated_by_user_id' => (int) $user->getKey(),
        'file_path' => $filePath,
        'file_disk' => 'exports',
    ]);

    $signedUrl = app(ReviewPackService::class)->generateDownloadUrl($pack);

    $this->actingAs($user)->get($signedUrl)->assertOk();
});

it('disables generate action for readonly member', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    Livewire::actingAs($user)
        ->test(ListReviewPacks::class)
        ->assertActionVisible('generate_pack')
        ->assertActionDisabled('generate_pack')
        ->assertActionExists('generate_pack', fn ($action): bool => $action->getTooltip() === UiTooltips::insufficientPermission());
});

// ─── REVIEW_PACK_MANAGE Member ──────────────────────────────

it('allows owner to generate a review pack', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    Livewire::actingAs($user)
        ->test(ListReviewPacks::class)
        ->assertActionVisible('generate_pack')
        ->assertActionEnabled('generate_pack');
});

it('allows owner to expire a ready pack', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $filePath = 'review-packs/expire-rbac.zip';
    Storage::disk('exports')->put($filePath, 'PK-fake');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'initiated_by_user_id' => (int) $user->getKey(),
        'file_path' => $filePath,
        'file_disk' => 'exports',
    ]);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    Livewire::actingAs($user)
        ->test(ListReviewPacks::class)
        ->assertTableActionVisible('expire', $pack)
        ->callTableAction('expire', $pack);

    $pack->refresh();
    expect($pack->status)->toBe(ReviewPackStatus::Expired->value);
});

it('disables expire action for readonly member', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'readonly');

    $filePath = 'review-packs/expire-readonly.zip';
    Storage::disk('exports')->put($filePath, 'PK-fake');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
        'file_path' => $filePath,
        'file_disk' => 'exports',
    ]);

    $tenant->makeCurrent();
    Filament::setTenant($tenant, true);

    Livewire::actingAs($user)
        ->test(ListReviewPacks::class)
        ->assertTableActionVisible('expire', $pack)
        ->assertTableActionDisabled('expire', $pack);
});

// ─── Signed URL Security ────────────────────────────────────

it('rejects unsigned download URL with 403', function (): void {
    $tenant = Tenant::factory()->create();
    [$user, $tenant] = createUserWithTenant(tenant: $tenant, role: 'owner');

    $pack = ReviewPack::factory()->ready()->create([
        'tenant_id' => (int) $tenant->getKey(),
        'workspace_id' => (int) $tenant->workspace_id,
    ]);

    $response = $this->actingAs($user)
        ->get(route('admin.review-packs.download', ['reviewPack' => $pack->getKey()]));

    $response->assertForbidden();
});
