<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Models\Workspace;
use App\Support\Workspaces\WorkspaceContext;
use App\Support\Workspaces\WorkspaceResolver;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureWorkspaceMember
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (! $user instanceof User) {
            return $next($request);
        }

        $workspaceParam = $request->route()?->parameter('workspace');

        $workspace = $workspaceParam instanceof Workspace
            ? $workspaceParam
            : (is_scalar($workspaceParam)
                ? app(WorkspaceResolver::class)->resolve((string) $workspaceParam)
                : null);

        if (! $workspace instanceof Workspace) {
            abort(404);
        }

        /** @var WorkspaceContext $context */
        $context = app(WorkspaceContext::class);

        if (! $context->isMember($user, $workspace)) {
            abort(404);
        }

        $context->setCurrentWorkspace($workspace, $user, $request);

        return $next($request);
    }
}
