<?php

namespace App\Http\Middleware;

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

class CheckStudentProfileStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $user = Auth::user();

        // Only apply to authenticated users, and presumably students
        // You might want to check roles here, e.g., $user->hasRole('student')
        if (! $user) {
            return $next($request);
        }

        // 0. Redirect Admin to Admin Panel
        if ($user->hasRole('super_admin')) {
            return redirect()->route('filament.admin.pages.dashboard');
        }

        // Exemptions: Allow logout, application form, and status page
        // Route names might vary, check common patterns
        $routeName = $request->route()->getName();
        $exemptRoutes = [
            'filament.student.auth.logout',
            'filament.student.pages.application-form',
            'filament.student.pages.application-status',
            // Also potential Livewire routes for file uploads/validation
            'livewire.update',
            'livewire.upload-file',
            'livewire.preview-file',
        ];

        if (in_array($routeName, $exemptRoutes) || str_contains($routeName, 'livewire')) {
            return $next($request);
        }

        $profile = $user->studentProfile;

        // 1. No Profile -> Redirect to Application Form
        if (! $profile) {
            return redirect()->route('filament.student.pages.application-form');
        }

        // 2. Pending or Rejected -> Redirect to Status Page
        // Note: Logic says "user will only see a page... once approved he can access portal"
        if (in_array($profile->verification_status, ['pending', 'rejected'])) {
            // If rejected, allow access to Form to re-submit?
            // The ApplicationForm logic handles updates, but the status page links to it.
            // If status is rejected, user might be trying to access Form, which is exempt.
            // If user tries to access Dashboard, redirect to Status.
            return redirect()->route('filament.student.pages.application-status');
        }

        return $next($request);
    }
}
