<?php

namespace Tests\Feature\Auth;

use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\PermissionCode;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Permission;
use App\Domains\Authorization\Models\Role;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class ScannerMeControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_returns_only_scanner_menus_assigned_to_the_tenant(): void
    {
        $scannerRole = Role::query()->create([
            'codigo' => RoleCode::Scanner->value,
            'nombre' => 'Scanner',
        ]);
        $permission = Permission::query()->create([
            'codigo' => PermissionCode::ScanTickets->value,
            'nombre' => 'Escanear tickets',
        ]);
        $scannerRole->permissions()->attach($permission->codigo);
        $tenant = Tenant::query()->create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.test',
        ]);
        $home = Menu::query()->create([
            'code' => 'scanner.inicio',
            'label' => 'Inicio',
            'route' => '/scanner/inicio',
        ]);
        $scan = Menu::query()->create([
            'code' => 'scanner.scan',
            'label' => 'Escanear',
            'route' => '/scanner/scan',
        ]);
        $foreign = Menu::query()->create([
            'code' => 'adminapp.inicio',
            'label' => 'Administración',
            'route' => '/admin/inicio',
        ]);

        $scannerRole->menus()->sync([$home->code, $scan->code]);
        $tenant->menues()->sync([$home->code, $scan->code, $foreign->code]);

        $user = User::factory()->create([
            'rol_codigo' => $scannerRole->codigo,
            'tenant_codigo' => $tenant->codigo,
        ]);
        Sanctum::actingAs($user);

        $this->getJson('/api/v1/scanner/me')
            ->assertOk()
            ->assertJsonPath('data.user.id', $user->id)
            ->assertJsonPath('data.tenant.codigo', $tenant->codigo)
            ->assertJsonCount(2, 'data.tenant.menues')
            ->assertJsonMissing(['code' => $foreign->code]);
    }
}
