<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Domain\Identity\Services\PermissionService;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    public function __construct(
        private readonly PermissionService $permissionService,
    ) {}

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

        if (!$user) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'Unauthenticated.'], 401);
            }
            return redirect()->route('login');
        }

        if (!$this->permissionService->can($user, $permission)) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'غير مصرح لك بهذا الإجراء'], 403);
            }
            abort(403, 'غير مصرح لك بهذا الإجراء');
        }

        return $next($request);
    }
}
