<?php

namespace App\Http\Middleware;

use App\Models\User;
use App\Support\Authorization\PermissionCatalog;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class EnsureUserIsOwner
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();

        if (!$user || !$user->is_active) {
            abort(403);
        }

        if (!in_array($user->role, [User::ROLE_CLIENT, User::ROLE_OWNER_STAFF], true)) {
            return redirect()->to(PermissionCatalog::firstAccessibleRouteFor($user));
        }

        return $next($request);
    }
}
