<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers;

use Builder\Core\Foundation\Dashboard\Widgets\Widget;
use Builder\Core\Foundation\Registry;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

final class DashboardController
{
    public function __construct(private readonly Registry $registry) {}

    public function __invoke(Request $request): Response
    {
        $user = $request->user();

        // Collect user's hidden widget keys (requires HasBuilderAccess trait)
        $hiddenWidgetKeys = $user !== null && method_exists($user, 'hiddenWidgets') ? $user->hiddenWidgets() : [];

        // Collect user's permissions for widget gating
        $userPermissions = $user !== null && method_exists($user, 'builderPermissions') ? $user->builderPermissions() : ['*'];

        // All permission-gated widgets (preference filtering handled client-side)
        $permittedWidgets = array_values(array_filter(
            $this->registry->widgets(),
            function (Widget $widget) use ($userPermissions): bool {
                $perm = $widget->getPermission();

                if ($perm !== null && ! in_array('*', $userPermissions, true) && ! in_array($perm, $userPermissions, true)) {
                    return false;
                }

                return true;
            },
        ));

        return Inertia::render('Dashboard', [
            // Full permission-filtered list; Vue filters by hiddenWidgetKeys
            'widgets' => array_map(fn (Widget $w): array => $w->toArray(), $permittedWidgets),
            // User's current hidden widget keys for client-side initial state
            'hiddenWidgetKeys' => $hiddenWidgetKeys,
        ]);
    }
}
