<?php

namespace App\Http\Middleware;

use App\Core\Addon\AddonManager;
use App\Http\Middleware\ClientAccountSwitcher;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AddonClientareaAuth
{
    public function __construct(protected AddonManager $manager) {}

    public function handle(Request $request, Closure $next)
    {
        $name = $request->route('name');
        $addon = $this->manager->get($name);

        if (! $addon || ! $this->manager->isActive($name)) {
            abort(404);
        }

        // Register addon's clientarea permission at request-time so
        // ClientAccountSwitcher's permissionMap merge sees it.
        $perm = $this->validatePermissionToken($addon->meta('clientarea_permission', '__BLOCKED__'));
        ClientAccountSwitcher::registerPermission('store.auth.addons.dispatch', $perm);

        $auth = $addon->meta('clientarea_auth', 'required');

        if ($auth !== 'public') {
            // Default fail-closed: require client auth
            if (! Auth::guard('client')->check()) {
                return redirect()->route('store.auth.login');
            }

            // Apply switched-user gate inline
            return app(ClientAccountSwitcher::class)->handle($request, $next);
        }

        return $next($request);
    }

    protected function validatePermissionToken(string $token): string
    {
        if (in_array($token, ['__BLOCKED__', '__BASIC__'], true)) {
            return $token;
        }
        // Reuse PROCP whitelist if available
        if (method_exists(\App\Enums\ClientPermission::class, 'all')
            && in_array($token, \App\Enums\ClientPermission::all(), true)) {
            return $token;
        }

        return '__BLOCKED__'; // fail-closed
    }
}
