<?php

namespace Tests\Feature;

use App\Livewire\Issues\IssueManager;
use App\Livewire\Issues\IssueTable;
use App\Models\Issue;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

class IssuesTablePageTest extends TestCase
{
    use RefreshDatabase;

    private function memberWithIssue(): array
    {
        foreach (['view issues', 'create issues', 'edit issues', 'delete issues'] as $p) {
            Permission::findOrCreate($p);
        }

        $user = User::factory()->create();
        $user->givePermissionTo(['view issues', 'edit issues', 'delete issues']);

        $project = Project::create([
            'reference' => 'TBL-1',
            'name' => 'Proyecto Tabla',
            'address' => 'Calle Falsa 123',
            'lat' => 40.0,
            'lng' => -3.0,
            'start_date' => now()->toDateString(),
            'end_date_estimated' => now()->addMonths(6)->toDateString(),
            'status' => 'in_progress',
            'created_by' => $user->id,
        ]);
        $project->users()->attach($user->id, ['role_in_project' => 'supervisor']);

        $issue = Issue::create([
            'project_id' => $project->id,
            'title' => 'Grieta en muro',
            'status' => 'open',
            'priority' => 'high',
            'reported_by' => $user->id,
        ]);

        return [$user, $project, $issue];
    }

    public function test_issue_manager_renders_stats_and_table(): void
    {
        [$user, $project, $issue] = $this->memberWithIssue();

        Livewire::actingAs($user)
            ->test(IssueManager::class, ['project' => $project])
            ->assertOk()
            ->assertSee('Incidencias del proyecto')
            ->assertSeeLivewire(IssueTable::class);
    }

    public function test_issue_table_lists_and_resolves_an_issue(): void
    {
        [$user, $project, $issue] = $this->memberWithIssue();

        Livewire::actingAs($user)
            ->test(IssueTable::class, ['projectId' => $project->id])
            ->assertOk()
            ->assertSee('Grieta en muro')
            ->call('resolve', $issue->id);

        $this->assertEquals('resolved', $issue->fresh()->status);
    }

    public function test_issue_table_forbidden_for_non_member(): void
    {
        [, $project] = $this->memberWithIssue();

        $outsider = User::factory()->create();
        $outsider->givePermissionTo('view issues');

        Livewire::actingAs($outsider)
            ->test(IssueTable::class, ['projectId' => $project->id])
            ->assertForbidden();
    }
}
