<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Company;
use App\Models\DashboardSnapshot;
use App\Services\Dashboard\DashboardTrendService;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class DashboardTrendServiceTest extends TestCase
{
    use DatabaseTransactions;

    private function seedWeekAgo(int $companyId, array $vals): void
    {
        DashboardSnapshot::create(array_merge([
            'company_id' => $companyId,
            'snapshot_date' => now()->subDays(7)->toDateString(),
            'created_at' => now(),
        ], $vals));
    }

    #[Test]
    public function it_computes_deltas_with_correct_polarity(): void
    {
        $company = Company::factory()->create();
        $this->seedWeekAgo($company->id, [
            'business_total' => 100000,
            'cash_base' => 50000,
            'por_cobrar' => 80000,
            'overdue' => 8000,
            'delinquency_rate' => 10,
        ]);

        $trends = app(DashboardTrendService::class)->trendsFor($company->id, [
            'business_total' => 120000,   // +20% ↑ bueno
            'cash_base' => 45000,         // -10% ↓ malo (caja ↑=bueno)
            'por_cobrar' => 80000,        //   0% neutral → good=true (>=0)
            'delinquency_rate' => 8,      // -20% ↓ bueno (mora ↓=bueno)
        ]);

        $this->assertEquals(20.0, $trends['business_total']['pct']);
        $this->assertTrue($trends['business_total']['good']);

        $this->assertEquals(-10.0, $trends['cash_base']['pct']);
        $this->assertFalse($trends['cash_base']['good']);

        $this->assertEquals(-20.0, $trends['delinquency_rate']['pct']);
        $this->assertTrue($trends['delinquency_rate']['good']);
    }

    #[Test]
    public function it_returns_null_during_ramp_up_and_on_zero_base(): void
    {
        $company = Company::factory()->create();

        // Sin snapshot en ventana → todo null.
        $trends = app(DashboardTrendService::class)->trendsFor($company->id, [
            'business_total' => 100,
            'cash_base' => 0,
            'por_cobrar' => 0,
            'delinquency_rate' => 5,
        ]);
        $this->assertNull($trends['business_total']);

        // Snapshot con base 0 → pct null (evita división por cero).
        $this->seedWeekAgo($company->id, [
            'business_total' => 0, 'cash_base' => 0, 'por_cobrar' => 0,
            'overdue' => 0, 'delinquency_rate' => 0,
        ]);
        $trends = app(DashboardTrendService::class)->trendsFor($company->id, [
            'business_total' => 100, 'cash_base' => 0, 'por_cobrar' => 0, 'delinquency_rate' => 5,
        ]);
        $this->assertNull($trends['business_total']);
    }
}
