<?php

declare(strict_types=1);

namespace Tests\Feature\Pwa;

use App\Models\Company;
use App\Models\DashboardSnapshot;
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 AdminDashboardStockTrendsTest extends TestCase
{
    use DatabaseTransactions;

    private function admin(Company $company): User
    {
        Role::firstOrCreate(['name' => 'admin', 'guard_name' => 'web']);
        $plan = Plan::factory()->create(['has_pwa_access' => true]);
        Subscription::factory()->active()->create([
            'company_id' => $company->id, 'plan_id' => $plan->id, 'ends_at' => now()->addYear(),
        ]);
        $u = User::factory()->create(['company_id' => $company->id]);
        $u->assignRole('admin');

        return $u->fresh();
    }

    #[Test]
    public function admin_payload_carries_stock_trend_when_a_week_old_snapshot_exists(): void
    {
        $company = Company::factory()->create();
        DashboardSnapshot::create([
            'company_id' => $company->id,
            'snapshot_date' => now()->subDays(7)->toDateString(),
            'business_total' => 100, 'cash_base' => 50, 'por_cobrar' => 80,
            'overdue' => 8, 'delinquency_rate' => 10, 'created_at' => now(),
        ]);

        Sanctum::actingAs($this->admin($company));

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

        // Las claves de stock llevan trend_pct/good (empresa vacía → business_total vivo = 0,
        // base 100 → pct = -100). Basta con que la clave EXISTA y sea numérica.
        $this->assertArrayHasKey('trend_pct', $stats['business_total']);
        $this->assertIsNumeric($stats['business_total']['trend_pct']);
        $this->assertArrayHasKey('delinquency_trend', $stats);
    }

    #[Test]
    public function trend_is_null_during_ramp_up(): void
    {
        $company = Company::factory()->create();
        Sanctum::actingAs($this->admin($company));

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

        $this->assertNull($stats['business_total']['trend_pct']);
        $this->assertNull($stats['delinquency_trend']);
    }
}
