<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthenticateSession
{
    public function handle(Request $request, Closure $next)
    {
        // 1. If not logged in via Auth and has user_id in session, restore Auth user
        if (!Auth::check() && $request->session()->has('user_id')) {
            $user = User::find($request->session()->get('user_id'));
            if ($user && $user->active && !$user->is_locked) {
                Auth::login($user);
            }
        }

        // 2. If logged in via Auth, keep session user_id synchronized
        if (Auth::check()) {
            $user = Auth::user();
            if (!$user->active || $user->is_locked) {
                Auth::logout();
                $request->session()->invalidate();
                return redirect()->route('login')->with('error', 'Your account has been deactivated or locked.');
            }
            $request->session()->put('user_id', $user->id);
            return $next($request);
        }

        // 3. Not authenticated
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        return redirect()->route('login');
    }
}
