<?php

namespace Tests\Unit;

use App\Models\Event;
use App\Models\EventMember;
use App\Models\Tenant;
use App\Models\User;
use App\Support\TenantMemberPermissions;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Tests\TestCase;

class TenantMemberPermissionsTest extends TestCase
{
    use RefreshDatabase;

    public function test_resolves_permissions_for_member(): void
    {
        $tenant = Tenant::factory()->create();
        $event = Event::factory()->for($tenant)->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'member',
        ]);

        EventMember::factory()->create([
            'tenant_id' => $tenant->id,
            'event_id' => $event->id,
            'user_id' => $user->id,
            'email' => $user->email,
            'status' => 'active',
            'permissions' => ['photos:moderate', 'tasks:manage'],
        ]);

        $request = Request::create('/');
        $request->setUserResolver(fn () => $user);

        $permissions = TenantMemberPermissions::resolveEventPermissions($request, $event);

        $this->assertContains('photos:moderate', $permissions);
        $this->assertContains('tasks:manage', $permissions);
    }

    public function test_allows_wildcard_permissions(): void
    {
        $tenant = Tenant::factory()->create();
        $event = Event::factory()->for($tenant)->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'member',
        ]);

        EventMember::factory()->create([
            'tenant_id' => $tenant->id,
            'event_id' => $event->id,
            'user_id' => $user->id,
            'email' => $user->email,
            'status' => 'active',
            'permissions' => ['photos:*'],
        ]);

        $request = Request::create('/');
        $request->setUserResolver(fn () => $user);

        $this->assertTrue(TenantMemberPermissions::allowsEventPermission($request, $event, 'photos:moderate'));
    }

    public function test_denies_missing_permissions(): void
    {
        $tenant = Tenant::factory()->create();
        $event = Event::factory()->for($tenant)->create();
        $user = User::factory()->create([
            'tenant_id' => $tenant->id,
            'role' => 'member',
        ]);

        EventMember::factory()->create([
            'tenant_id' => $tenant->id,
            'event_id' => $event->id,
            'user_id' => $user->id,
            'email' => $user->email,
            'status' => 'active',
            'permissions' => ['tasks:manage'],
        ]);

        $request = Request::create('/');
        $request->setUserResolver(fn () => $user);

        $this->expectException(HttpResponseException::class);

        TenantMemberPermissions::ensureEventPermission($request, $event, 'photos:moderate');
    }
}
