<?php

namespace App\Http\Middleware;

use App\Services\Care\OrganizationResolver;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureOrganizationSetup
{
    public function __construct(
        protected OrganizationResolver $organizations,
    ) {}

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if (! $user) {
            return $next($request);
        }

        if ($request->routeIs('care.onboarding*')) {
            return $next($request);
        }

        if (! $this->organizations->isOnboarded($user)) {
            // Staff already attached to a tenant must not see owner onboarding.
            if ($this->organizations->membershipFor($user)) {
                abort(403, 'Your facility setup is incomplete. Ask an administrator to finish onboarding.');
            }

            return redirect()->route('care.onboarding.show');
        }

        return $next($request);
    }
}
