<?php

declare(strict_types=1);

namespace Tests\Feature;

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

/**
 * El bloqueo de límites del plan también aplica en la PWA (cobradores en calle),
 * no solo en el panel. Aquí se prueba el endpoint de creación de clientes.
 */
class PwaPlanLimitTest extends TestCase
{
    use DatabaseTransactions;

    protected function setUp(): void
    {
        parent::setUp();
        Role::firstOrCreate(['name' => 'collector', 'guard_name' => 'web']);
    }

    private function collectorFor(Company $company): User
    {
        $user = User::factory()->create(['company_id' => $company->id]);
        $user->assignRole('collector');

        return $user;
    }

    /** @param array<string,int> $limits */
    private function companyOnPlan(array $limits): Company
    {
        $plan = Plan::factory()->create(array_merge([
            'max_users' => 0, 'max_collectors' => 0, 'max_active_credits' => 0,
            'max_clients' => 0, 'max_monthly_volume' => 0,
        ], $limits));

        $company = Company::factory()->create();
        Subscription::factory()->active()->create([
            'company_id' => $company->id,
            'plan_id' => $plan->id,
            'ends_at' => now()->addYear(),
        ]);

        return $company->refresh();
    }

    #[Test]
    public function pwa_client_creation_is_blocked_over_the_plan_limit(): void
    {
        $company = $this->companyOnPlan(['max_clients' => 1]);
        Client::factory()->create(['company_id' => $company->id]); // ya en el tope (1/1)

        $response = $this->actingAs($this->collectorFor($company), 'sanctum')
            ->postJson('/api/pwa/clients', [
                'name' => 'Cliente Nuevo',
                'identification' => 'CC-'.uniqid(),
                'phone' => '3001234567',
            ]);

        $response->assertStatus(422);
        $this->assertStringContainsString('límite', (string) $response->json('message'));
        $this->assertSame(1, Client::where('company_id', $company->id)->count()); // no se creó
    }

    #[Test]
    public function pwa_client_creation_succeeds_under_the_limit(): void
    {
        $company = $this->companyOnPlan(['max_clients' => 5]);

        $this->actingAs($this->collectorFor($company), 'sanctum')
            ->postJson('/api/pwa/clients', [
                'name' => 'Cliente Nuevo',
                'identification' => 'CC-'.uniqid(),
                'phone' => '3001234567',
            ])
            ->assertStatus(201);

        $this->assertSame(1, Client::where('company_id', $company->id)->count());
    }
}
