<?php

namespace App\Http\Controllers\Api\V1\Admin\User;

use App\Models\AdminRole;
use App\Support\ApiResponse;
use App\Support\AdminAuthorizationRegistry;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Support\AdminRoleApiPresenter;

/** GET /api/v1/admin/admin-user-permission-catalog */
final class AdminPermissionCatalogController extends Controller
{
    public function __invoke(): JsonResponse
    {
        /** @var list<array{slug: string, name: string}> */
        $catalog = config('admin_permissions.catalog', []);
        /** @var list<array{key: string, label: string, slugs: list<string>}> $groupDefs */
        $groupDefs = config('admin_permissions.catalog_menu_groups', []);

        $catalogBySlug = collect($catalog)->keyBy('slug');

        $permissions = collect($catalog)->values()->map(static fn (array $row, int $index): array => [
            'id' => $index + 1,
            'slug' => $row['slug'],
            'name' => $row['name'],
        ])->all();

        $permissionIdBySlug = collect($permissions)->keyBy('slug')->map(static fn (array $row): int => $row['id'])->all();

        $permissionMenuGroups = [];
        foreach ($groupDefs as $g) {
            $rows = [];
            foreach ($g['slugs'] as $slug) {
                $meta = $catalogBySlug->get($slug);
                if ($meta === null) {
                    continue;
                }
                $id = $permissionIdBySlug[$slug] ?? null;
                if ($id === null) {
                    continue;
                }
                $rows[] = [
                    'id' => (int) $id,
                    'slug' => $slug,
                    'name' => $meta['name'],
                ];
            }
            if ($rows !== []) {
                $permissionMenuGroups[] = [
                    'key' => $g['key'],
                    'label' => $g['label'],
                    'permissions' => $rows,
                ];
            }
        }

        $roles = AdminRole::query()
            ->where('scope_type', AdminRole::SCOPE_SYSTEM)
            ->orderBy('slug')
            ->get(['id', 'slug', 'name']);

        return ApiResponse::success([
            'permissions' => $permissions,
            'permission_menu_groups' => $permissionMenuGroups,
            'navigation' => AdminAuthorizationRegistry::navigationItems(),
            'roles' => $roles->map(static fn (AdminRole $role): array => AdminRoleApiPresenter::item($role))->values()->all(),
        ]);
    }
}
