<?php

namespace Tests\Feature\Forms;

use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Catalog\Models\Category;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class AdminAppStaffFormControllerTest extends TestCase
{
    use RefreshDatabase;

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

        $this->seed(AuthorizationSeeder::class);
        WebsiteType::query()->create([
            'codigo' => 'onticket',
            'nombre' => 'OnTicket',
        ]);
    }

    public function test_authentication_is_required(): void
    {
        $this->getJson('/api/v1/adminapp/forms/staff')->assertUnauthorized();
    }

    public function test_adminapp_user_gets_only_its_tenant_categories(): void
    {
        $tenant = $this->createTenant('acme');
        $otherTenant = $this->createTenant('other');
        $category = Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'nombre' => 'Bebidas',
        ]);
        Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'categoria_id' => $category->id,
            'nombre' => 'Gaseosas',
        ]);
        Category::query()->create([
            'tenant_code' => $otherTenant->codigo,
            'nombre' => 'Privada',
        ]);
        Sanctum::actingAs(User::factory()->create([
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => $tenant->codigo,
        ]));

        $this->getJson('/api/v1/adminapp/forms/staff')
            ->assertOk()
            ->assertJsonCount(1, 'data.categories')
            ->assertJsonPath('data.categories.0.id', $category->id)
            ->assertJsonPath('data.categories.0.nombre', 'Bebidas')
            ->assertJsonMissingPath('data.categories.0.categoria_id')
            ->assertJsonMissingPath('data.roles');
    }

    public function test_customer_cannot_get_staff_form(): void
    {
        Sanctum::actingAs(User::factory()->create([
            'rol_codigo' => RoleCode::User->value,
        ]));

        $this->getJson('/api/v1/adminapp/forms/staff')->assertForbidden();
    }

    private function createTenant(string $code): Tenant
    {
        return Tenant::query()->create([
            'codigo' => $code,
            'nombre' => ucfirst($code),
            'dominio' => "{$code}.test",
            'website_type_code' => 'onticket',
        ]);
    }
}
