<?php

namespace Tests\Feature\Tenant;

use App\Models\Event;
use App\Models\EventMember;
use App\Models\User;
use Illuminate\Support\Facades\Hash;

class EventMemberControllerTest extends TenantTestCase
{
    public function test_admin_can_invite_member(): void
    {
        $event = Event::factory()->for($this->tenant)->create([
            'slug' => 'collab-event',
        ]);

        $payload = [
            'email' => 'new.member@example.com',
            'name' => 'New Member',
            'role' => 'member',
        ];

        $response = $this->authenticatedRequest('POST', "/api/v1/tenant/events/{$event->slug}/members", $payload);

        $response->assertCreated();
        $response->assertJsonPath('data.email', 'new.member@example.com');
        $response->assertJsonPath('data.role', 'member');

        $this->assertDatabaseHas(EventMember::class, [
            'event_id' => $event->id,
            'email' => 'new.member@example.com',
            'role' => 'member',
        ]);

        $this->assertDatabaseHas(User::class, [
            'email' => 'new.member@example.com',
            'tenant_id' => $this->tenant->id,
            'role' => 'member',
        ]);
    }

    public function test_member_token_can_access_photo_moderation_routes(): void
    {
        $event = Event::factory()->for($this->tenant)->create([
            'slug' => 'moderate-event',
        ]);

        $memberUser = User::factory()->create([
            'email' => 'member@example.com',
            'tenant_id' => $this->tenant->id,
            'role' => 'member',
            'password' => Hash::make('secret123'),
        ]);

        EventMember::factory()->create([
            'tenant_id' => $this->tenant->id,
            'event_id' => $event->id,
            'user_id' => $memberUser->id,
            'email' => $memberUser->email,
            'role' => 'member',
            'status' => 'active',
            'permissions' => ['photos:moderate'],
        ]);

        $login = $this->postJson('/api/v1/tenant-auth/login', [
            'login' => $memberUser->email,
            'password' => 'secret123',
        ]);

        $login->assertOk();
        $token = $login->json('token');

        $response = $this->withHeaders([
            'Authorization' => 'Bearer '.$token,
        ])->getJson("/api/v1/tenant/events/{$event->slug}/photos");

        $response->assertOk();
        $response->assertJsonStructure(['data']);
    }
}
