<?php

namespace Tests\Feature;

use App\Domain\Subscription\UsageService;
use App\Models\Plan;
use App\Models\Tenant;
use App\Support\Tenancy;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class UsageServiceTest extends TestCase
{
    use RefreshDatabase;

    protected Tenant $tenant;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();

        $this->tenant = Tenant::create(['name' => 'C', 'slug' => 'c']);
        $this->tenant->subscription()->create([
            'plan_id' => Plan::first()->id, 'status' => 'active',
            'starts_at' => now(), 'current_period_ends_at' => now()->addMonth(),
        ]);
        app(Tenancy::class)->set($this->tenant);
    }

    public function test_increment_and_used(): void
    {
        $svc = app(UsageService::class);
        $svc->increment($this->tenant, 'wa_messages', 3);
        $svc->increment($this->tenant, 'wa_messages');

        $this->assertSame(4, $svc->used($this->tenant, 'wa_messages'));
    }

    public function test_levels_ok_warn_over(): void
    {
        $svc = app(UsageService::class);
        $limit = $this->tenant->subscription->plan->limit('wa_messages_month');
        $this->assertNotNull($limit);

        // ok
        $svc->increment($this->tenant, 'wa_messages', (int) floor($limit * 0.5));
        $this->assertSame('ok', $svc->status($this->tenant)['level']);

        // warn (>= 80%)
        $svc->increment($this->tenant, 'wa_messages', (int) ceil($limit * 0.35));
        $this->assertSame('warn', $svc->status($this->tenant)['level']);

        // over (>= 100%)
        $svc->increment($this->tenant, 'wa_messages', $limit);
        $this->assertSame('over', $svc->status($this->tenant)['level']);
    }

    public function test_soft_limit_never_blocks_sending(): void
    {
        // Sending past the limit still records usage (no exception thrown).
        $svc = app(UsageService::class);
        $limit = (int) $this->tenant->subscription->plan->limit('wa_messages_month');
        $svc->increment($this->tenant, 'wa_messages', $limit + 100);

        $status = $svc->status($this->tenant);
        $this->assertSame('over', $status['level']);
        $this->assertGreaterThan($limit, $status['used']);
    }
}
