<?php

declare(strict_types=1);

use App\Filament\Resources\AlertRuleResource;
use App\Models\AlertRule;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceCapabilityResolver;

it('returns 404 when a workspace member tries to edit a rule from another workspace', function (): void {
    [$user] = createUserWithTenant(role: 'owner');

    $otherWorkspace = Workspace::factory()->create();
    $rule = AlertRule::factory()->create([
        'workspace_id' => (int) $otherWorkspace->getKey(),
    ]);

    $this->actingAs($user)
        ->get(AlertRuleResource::getUrl('edit', ['record' => $rule], panel: 'admin'))
        ->assertNotFound();
});

it('returns 403 for members missing alerts view capability on rules index', function (): void {
    $workspace = Workspace::factory()->create();
    $user = User::factory()->create();

    WorkspaceMembership::factory()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'user_id' => (int) $user->getKey(),
        'role' => 'readonly',
    ]);

    $resolver = \Mockery::mock(WorkspaceCapabilityResolver::class);
    $resolver->shouldReceive('isMember')->andReturnTrue();
    $resolver->shouldReceive('can')->andReturnFalse();
    app()->instance(WorkspaceCapabilityResolver::class, $resolver);

    session()->put(\App\Support\Workspaces\WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    $this->actingAs($user)
        ->get(AlertRuleResource::getUrl(panel: 'admin'))
        ->assertForbidden();
});

it('allows members with alerts view but forbids create for members without alerts manage', function (): void {
    [$user] = createUserWithTenant(role: 'readonly');

    $this->actingAs($user)
        ->get(AlertRuleResource::getUrl(panel: 'admin'))
        ->assertOk();

    $this->actingAs($user)
        ->get(AlertRuleResource::getUrl('create', panel: 'admin'))
        ->assertForbidden();
});
