<?php

declare(strict_types=1);

namespace Tests\Feature\Pwa;

use App\Models\Company;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Event;
use Laravel\Sanctum\Sanctum;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

/**
 * Tests de integración para los endpoints del DashboardController.
 *
 * Verifica que cada endpoint devuelve HTTP 200 y la estructura
 * JSON esperada (claves de primer nivel).
 */
class DashboardEndpointsTest extends TestCase
{
    use DatabaseTransactions;

    private Company $company;

    private User $collector;

    protected function setUp(): void
    {
        parent::setUp();

        Event::fake(); // Evitar listeners asíncronos que puedan interferir

        // Crear roles necesarios para pwa.access middleware
        foreach (['admin', 'supervisor', 'collector'] as $role) {
            Role::firstOrCreate(['name' => $role, 'guard_name' => 'web']);
        }

        // Empresa con plan y suscripción activa (requeridos por EnsurePwaAccess)
        $plan = Plan::factory()->create(['has_pwa_access' => true]);
        $this->company = Company::factory()->create();

        Subscription::factory()->active()->create([
            'company_id' => $this->company->id,
            'plan_id' => $plan->id,
            'ends_at' => now()->addYear(),
        ]);

        // Collector autenticado vía Sanctum
        $this->collector = User::factory()->create([
            'company_id' => $this->company->id,
        ]);
        $this->collector->assignRole('collector');

        Sanctum::actingAs($this->collector->fresh());
    }

    /**
     * GET /api/pwa/dashboard/summary devuelve 200 con las claves esperadas.
     */
    public function test_summary_returns_expected_structure(): void
    {
        $response = $this->getJson('/api/pwa/dashboard/summary');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'urgent_count',
                'last_sync',
            ]);
    }

    /**
     * GET /api/pwa/dashboard/weekly-progress devuelve 200 con las claves esperadas.
     */
    public function test_weekly_progress_returns_expected_structure(): void
    {
        $response = $this->getJson('/api/pwa/dashboard/weekly-progress');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'data',
                'meta',
            ]);
    }

    /**
     * GET /api/pwa/dashboard/recent-payments devuelve 200 con las claves esperadas.
     */
    public function test_recent_payments_returns_expected_structure(): void
    {
        $response = $this->getJson('/api/pwa/dashboard/recent-payments');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'data',
                'meta',
            ]);
    }

    /**
     * GET /api/pwa/dashboard/pending-collections devuelve 200 con las claves esperadas.
     */
    public function test_pending_collections_returns_expected_structure(): void
    {
        $response = $this->getJson('/api/pwa/dashboard/pending-collections');

        $response->assertStatus(200)
            ->assertJsonStructure([
                'data',
                'by_priority',
                'meta',
            ]);
    }
}
