<?php

namespace App\Http\Middleware;

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

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

        if (! $user) {
            return $next($request);
        }

        if ($user->isSuperAdmin()) {
            return redirect()
                ->route('super.dashboard')
                ->with('warning', 'Use the tenant Manage button to enter a tenant portal before opening tenant pages.');
        }

        $tenant = $user->tenant;

        if (! $tenant) {
            Auth::logout();

            return redirect()->route('login')->withErrors(['email' => 'This account is not attached to an active company.']);
        }

        if ($request->session()->has('impersonating_super_admin_id')) {
            return $next($request);
        }

        if ($tenant->status === 'suspended') {
            Auth::logout();

            return redirect()->route('login')->withErrors(['email' => 'This company account has been suspended. Contact support.']);
        }

        if ($tenant->status !== 'active') {
            Auth::logout();

            return redirect()->route('login')->withErrors(['email' => 'Your company registration is still pending approval.']);
        }

        if ($tenant->isExpired() && ! $request->routeIs('tenant.billing.*', 'logout')) {
            return redirect()->route('tenant.billing.index')
                ->with('warning', 'Your subscription has expired. Submit a renewal payment to continue.');
        }

        return $next($request);
    }
}
