<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Core\MiddlewareInterface;
use App\Core\PlatformAuth;
use App\Core\Request;
use App\Core\Response;

/**
 * PlatformAdminMiddleware
 *
 * Attach to every route under the admin.<APP_DOMAIN> console via
 * ->get(..., middleware: ['platform_admin']). Mirrors AuthMiddleware's
 * shape but checks PlatformAuth, never Auth — a logged-in CRM user
 * (even one with an "Admin" role inside their own tenant) has no
 * access here.
 */
final class PlatformAdminMiddleware implements MiddlewareInterface
{
    public function handle(Request $request, callable $next): Response
    {
        if (PlatformAuth::guest()) {
            if ($request->isAjax() || $request->isJson()) {
                return \App\Helpers\AjaxResponse::unauthorized();
            }

            return Response::redirect(base_url('platform/login'));
        }

        return $next($request);
    }
}
