<?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 Laravel\Sanctum\Sanctum;
use PHPUnit\Framework\Attributes\Test;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class DashboardCollectionsTrendTest extends TestCase
{
    use DatabaseTransactions;

    private function company(): Company
    {
        $plan = Plan::factory()->create(['has_pwa_access' => true]);
        $company = Company::factory()->create();
        Subscription::factory()->active()->create([
            'company_id' => $company->id,
            'plan_id' => $plan->id,
            'ends_at' => now()->addYear(),
        ]);

        return $company;
    }

    #[Test]
    public function admin_and_supervisor_dashboards_expose_a_collections_trend(): void
    {
        // El sparkline del DUEÑO paso de 7 a 30 dias (spec 2026-09-08 §B bloque 4):
        // su panel muestra el ritmo del mes. El del supervisor sigue en 7 —
        // su vista es de operacion diaria del equipo, no de negocio.
        $diasEsperados = ['admin' => 30, 'supervisor' => 7];

        foreach (['admin', 'supervisor'] as $role) {
            Role::firstOrCreate(['name' => $role, 'guard_name' => 'web']);
            $company = $this->company();
            $user = User::factory()->create(['company_id' => $company->id]);
            $user->assignRole($role);
            Sanctum::actingAs($user->fresh());

            $stats = $this->getJson('/api/pwa/dashboard')
                ->assertStatus(200)
                ->json('stats');

            $this->assertArrayHasKey('collections_trend', $stats, "{$role} tiene collections_trend");
            $this->assertCount(
                $diasEsperados[$role],
                $stats['collections_trend'],
                "serie de {$diasEsperados[$role]} dias para {$role}"
            );
            $this->assertArrayHasKey('date', $stats['collections_trend'][0]);
            $this->assertArrayHasKey('amount', $stats['collections_trend'][0]);

            $this->assertArrayHasKey('collected_trend', $stats);
            $this->assertArrayHasKey('pct', $stats['collected_trend']);
            $this->assertArrayHasKey('good', $stats['collected_trend']);
        }
    }
}
