<?php

namespace Tests\Unit\Services;

use App\Events\Packages\TenantPackageEventLimitReached;
use App\Events\Packages\TenantPackageEventThresholdReached;
use App\Models\Package;
use App\Models\Tenant;
use App\Models\TenantPackage;
use App\Services\Packages\TenantUsageTracker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Event as EventFacade;
use Tests\TestCase;

class TenantUsageTrackerTest extends TestCase
{
    use RefreshDatabase;

    public function test_record_event_usage_dispatches_threshold_and_updates_columns(): void
    {
        EventFacade::fake([
            TenantPackageEventThresholdReached::class,
            TenantPackageEventLimitReached::class,
        ]);

        Config::set('package-limits.event_thresholds', [0.5]);

        $tenant = Tenant::factory()->create();
        $package = Package::factory()->reseller()->create([
            'max_events_per_year' => 10,
        ]);

        $tenantPackage = TenantPackage::factory()
            ->for($tenant)
            ->for($package)
            ->create([
                'used_events' => 6,
            ])->fresh();

        /** @var TenantUsageTracker $tracker */
        $tracker = app(TenantUsageTracker::class);

        $tracker->recordEventUsage($tenantPackage, 4, 2);

        EventFacade::assertDispatched(TenantPackageEventThresholdReached::class);
        EventFacade::assertNotDispatched(TenantPackageEventLimitReached::class);

        $tenantPackage->refresh();

        $this->assertNotNull($tenantPackage->event_warning_sent_at);
        $this->assertSame(0.5, (float) $tenantPackage->event_warning_threshold);
    }

    public function test_record_event_usage_dispatches_limit_and_sets_timestamp(): void
    {
        EventFacade::fake([
            TenantPackageEventThresholdReached::class,
            TenantPackageEventLimitReached::class,
        ]);

        Config::set('package-limits.event_thresholds', [0.5]);

        $tenant = Tenant::factory()->create();
        $package = Package::factory()->reseller()->create([
            'max_events_per_year' => 3,
        ]);

        $tenantPackage = TenantPackage::factory()
            ->for($tenant)
            ->for($package)
            ->create([
                'used_events' => 3,
            ])->fresh();

        /** @var TenantUsageTracker $tracker */
        $tracker = app(TenantUsageTracker::class);

        $tracker->recordEventUsage($tenantPackage, 2, 1);

        EventFacade::assertDispatched(TenantPackageEventLimitReached::class);

        $tenantPackage->refresh();

        $this->assertNotNull($tenantPackage->event_limit_notified_at);
        $this->assertFalse($tenantPackage->active);
    }
}
