<?php

namespace Tests\Feature\Dashboard;

use App\Models\Auth\User;
use App\Models\Clients\Client;
use App\Models\Products\LicenseToken;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Cache;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;

/**
 * El bloque "Requiere tu atención" no pagina: muestra las N más urgentes de cada
 * origen y resume el resto en una fila. Lo que se fija aquí es que ese recorte
 * NUNCA sea silencioso —truncar sin decirlo hace leer "5 incidencias" donde hay
 * mil— y que el número de filas siga acotado por mucho volumen que haya.
 */
class DashboardTruncationTest extends TestCase
{
    use RefreshDatabase;

    private function admin(): User
    {
        $permisos = [
            'admin.dashboard.index',
            'admin.environments.index',
            'admin.clients.index',
            'admin.license-tokens.index',
            'admin.products.index',
            'admin.api-logs.index',
        ];

        foreach ($permisos as $nombre) {
            Permission::firstOrCreate(
                ['name' => $nombre, 'guard_name' => 'web'],
                ['model' => 'dashboard', 'description' => $nombre]
            );
        }

        $user = User::factory()->create();
        $user->givePermissionTo($permisos);
        $this->actingAs($user);

        Cache::flush();

        return $user;
    }

    private function licenciasQueVencen(int $cuantas): void
    {
        $cliente = Client::create(['name' => 'Cliente Masivo', 'shortname' => 'masivo', 'actived' => true]);

        for ($i = 1; $i <= $cuantas; $i++) {
            LicenseToken::create([
                'client_id' => $cliente->id,
                'name' => 'Licencia ' . $i,
                'token' => '3IP-MASIVA-' . $i,
                'active' => true,
                // Días distintos para que el orden por urgencia sea determinista.
                'end_at' => now()->addDays(1 + ($i % 29)),
            ]);
        }
    }

    public function test_cuando_hay_mas_de_las_que_caben_lo_dice_con_el_total(): void
    {
        $this->admin();
        $this->licenciasQueVencen(40);

        $this->get('/dashboard')
            ->assertOk()
            // 40 en total, 5 mostradas: quedan 35 ocultas y hay que verlo.
            ->assertSee('+35 más')
            ->assertSee('se muestran las 5 más urgentes de 40');
    }

    public function test_con_pocas_no_aparece_la_fila_de_resumen(): void
    {
        $this->admin();
        $this->licenciasQueVencen(3);

        $this->get('/dashboard')
            ->assertOk()
            ->assertDontSee('más urgentes de');
    }

    public function test_con_volumen_masivo_el_bloque_sigue_acotado(): void
    {
        // Lo que el Dashboard no puede hacer es crecer sin límite: son 500
        // licencias y el bloque tiene que seguir pintando 5 filas más el resumen.
        $this->admin();
        $this->licenciasQueVencen(500);

        $html = $this->get('/dashboard')->assertOk()->getContent();

        $this->assertSame(6, substr_count($html, 'class="dash-att"'));
        $this->assertStringContainsString('+495 más', $html);
    }
}
