<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckPermission
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string  $permission
     * @return mixed
     */
    public function handle(Request $request, Closure $next, string $permission): Response
    {
        $user = Auth::user();

        // If not authenticated via Auth but session exists, restore Auth session
        if (!$user && $request->session()->has('user_id')) {
            $candidate = User::find($request->session()->get('user_id'));
            if ($candidate && $candidate->active && !$candidate->is_locked) {
                Auth::login($candidate);
                $user = $candidate;
            }
        }

        // 1. Unauthenticated or locked out
        if (!$user) {
            if ($request->expectsJson()) {
                return response()->json(['error' => 'Unauthenticated'], 401);
            }
            return redirect()->route('login');
        }

        if ($user->is_locked || !$user->active) {
            Auth::logout();
            $request->session()->invalidate();
            return redirect()->route('login')->with('error', 'Your account has been deactivated or locked. Please contact your system administrator.');
        }

        // 2. Check Permission
        if (!$user->hasPermission($permission)) {
            if ($request->expectsJson()) {
                return response()->json([
                    'error'      => 'Forbidden',
                    'message'    => "You do not have permission to access this resource or action ({$permission}).",
                    'permission' => $permission,
                ], 403);
            }

            return response()->view('errors.403', [
                'permission' => $permission,
                'message'    => "You do not have the required capability ({$permission}) to perform this action or view this page."
            ], 403);
        }

        return $next($request);
    }
}
