<?php

namespace App\Http\Middleware;

use App\Services\Auth\PermissionCheckService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class RequirePermission
{
    public function __construct(private PermissionCheckService $permissions)
    {
    }

    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $userId = (int) ($request->user()?->id ?? 0);
        if ($userId <= 0) {
            return response()->json(['status' => false, 'message' => 'Unauthorized.'], 401);
        }

        if (!$this->permissions->hasPermission($userId, $permission)) {
            if ($request->expectsJson()) {
                return response()->json(['status' => false, 'message' => 'Access denied.'], 403);
            }
            return response()->json(['status' => false, 'message' => 'Access denied.'], 403);
        }

        return $next($request);
    }
}
