<?php

namespace App\Http\Middleware;

use App\Domains\Workspace\Models\Workspace;
use App\Domains\Workspace\Services\CurrentWorkspace;
use Closure;
use Illuminate\Http\Request;

class ResolveWorkspace
{
    public function __construct(private CurrentWorkspace $current) {}

    public function handle(Request $request, Closure $next): mixed
    {
        $ulid = $request->route('workspace');

        if (! $ulid) {
            return $next($request);
        }

        $workspace = Workspace::where('ulid', is_string($ulid) ? $ulid : $ulid->ulid)->firstOrFail();

        // 404 instead of 403 — don't leak existence across workspace boundaries
        $user = $request->user();
        $isMember = $user && $user->workspaceMemberships()->where('workspace_id', $workspace->id)->exists();
        $isOwner = $user && $workspace->owner_id === $user->id;
        if (! $isMember && ! $isOwner) {
            abort(404);
        }

        $this->current->set($workspace);
        $request->route()->setParameter('workspace', $workspace);

        return $next($request);
    }
}
