<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Client;
use App\Models\Company;
use App\Models\Credit;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

/**
 * Tests para Company::canCreateCredit() y Company::getUsageStats()
 *
 * Verifica que los créditos en estado overdue se cuentan como activos
 * a efectos del límite del plan.
 */
class CompanyCanCreateCreditTest extends TestCase
{
    use DatabaseTransactions;

    private Company $company;

    private Plan $plan;

    protected function setUp(): void
    {
        parent::setUp();

        // Plan con límite de exactamente 3 créditos activos
        $this->plan = Plan::factory()->create([
            'max_active_credits' => 3,
        ]);

        $this->company = Company::factory()->create();

        Subscription::factory()->create([
            'company_id' => $this->company->id,
            'plan_id' => $this->plan->id,
            'status' => Subscription::STATUS_ACTIVE,
            'is_active' => true,
            'starts_at' => now()->subMonth(),
            'ends_at' => now()->addYear(),
        ]);
    }

    private function makeCredit(string $status): Credit
    {
        $user = User::factory()->create(['company_id' => $this->company->id]);
        $client = Client::factory()->create(['company_id' => $this->company->id]);

        return Credit::factory()->create([
            'company_id' => $this->company->id,
            'client_id' => $client->id,
            'collector_user_id' => $user->id,
            'created_by_user_id' => $user->id,
            'status' => $status,
        ]);
    }

    // ------------------------------------------------------------------

    #[Test]
    public function can_create_credit_returns_false_when_limit_reached_with_overdue_credits(): void
    {
        // 1 active + 1 delayed + 1 overdue = 3 créditos activos → límite exacto alcanzado
        $this->makeCredit(Credit::STATUS_ACTIVE);
        $this->makeCredit(Credit::STATUS_DELAYED);
        $this->makeCredit(Credit::STATUS_OVERDUE);

        $this->company->unsetRelation('currentSubscription');

        $this->assertFalse(
            $this->company->canCreateCredit(),
            'canCreateCredit() debería retornar false cuando los 3 estados activos alcanzan el límite del plan.'
        );
    }

    #[Test]
    public function can_create_credit_returns_true_when_only_two_active_statuses_are_used(): void
    {
        // 1 active + 1 delayed = 2 créditos activos → aún hay espacio
        $this->makeCredit(Credit::STATUS_ACTIVE);
        $this->makeCredit(Credit::STATUS_DELAYED);

        $this->company->unsetRelation('currentSubscription');

        $this->assertTrue(
            $this->company->canCreateCredit(),
            'canCreateCredit() debería retornar true cuando hay capacidad restante.'
        );
    }

    #[Test]
    public function get_usage_stats_counts_overdue_credits_in_active_total(): void
    {
        $this->makeCredit(Credit::STATUS_ACTIVE);
        $this->makeCredit(Credit::STATUS_DELAYED);
        $this->makeCredit(Credit::STATUS_OVERDUE);

        $this->company->unsetRelation('currentSubscription');

        $stats = $this->company->getUsageStats();

        $this->assertSame(3, $stats['credits']['current'],
            'getUsageStats() debe contar los 3 estados activos (active + delayed + overdue).');

        $this->assertSame(100, $stats['credits']['percentage'],
            'Con 3/3 créditos el porcentaje de uso debe ser 100%.');
    }
}
