<?php

namespace Tests\Unit\Services\Monitoring;

use App\Services\Monitoring\PackageLimitMetrics;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Tests\TestCase;

class PackageLimitMetricsTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        config()->set('cache.default', 'array');
        Cache::flush();
        Log::spy();
    }

    public function test_records_gallery_metrics(): void
    {
        PackageLimitMetrics::recordGalleryWarning(7);
        PackageLimitMetrics::recordGalleryWarning(7);
        PackageLimitMetrics::recordGalleryExpired();

        $snapshot = PackageLimitMetrics::snapshot();

        $this->assertSame(2, $snapshot['gallery']['warning_day_7'] ?? null);
        $this->assertSame(1, $snapshot['gallery']['expired'] ?? null);

        Log::shouldHaveReceived('info')->atLeast()->once();
    }

    public function test_records_tenant_package_and_credit_metrics(): void
    {
        PackageLimitMetrics::recordTenantPackageWarning(6);
        PackageLimitMetrics::recordTenantPackageExpired();
        PackageLimitMetrics::recordCreditWarning(5, 4);
        PackageLimitMetrics::recordCreditRecovery(8);

        $snapshot = PackageLimitMetrics::snapshot();

        $this->assertSame(1, $snapshot['tenant_package']['warning_day_6'] ?? null);
        $this->assertSame(1, $snapshot['tenant_package']['expired'] ?? null);
        $this->assertSame(1, $snapshot['tenant_credit']['threshold_5'] ?? null);
        $this->assertSame(1, $snapshot['tenant_credit']['recovered'] ?? null);
    }

    public function test_reset_clears_metrics(): void
    {
        PackageLimitMetrics::recordGalleryWarning(1);
        $this->assertNotEmpty(PackageLimitMetrics::snapshot());

        PackageLimitMetrics::reset();

        $this->assertSame([], PackageLimitMetrics::snapshot());
    }
}
