<?php

namespace App\Http\Middleware;

use App\Services\TenantContext;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

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

        if ($user) {
            // Check User status
            if (in_array($user->status, ['suspended', 'locked', 'terminated', 'inactive'])) {
                auth()->logout();

                return redirect()->route('login')->withErrors([
                    'login' => 'Your user account is '.$user->status.'. Please contact your system administrator.',
                ]);
            }

            // Block tenant users from accessing /platform/* routes (Requirement 1 & 93)
            if ($request->is('platform*') && ! $user->isPlatformUser() && ! session()->has('impersonator_id')) {
                abort(403, 'Platform control panel access restricted to SaaS Super Admins.');
            }

            // Set Tenant Context
            if ($user->tenant_id) {
                $tenant = $user->tenant;
                if ($tenant) {
                    if (in_array($tenant->status, ['suspended', 'cancelled'])) {
                        return response()->view('errors.tenant_suspended', [
                            'tenant' => $tenant,
                            'status' => $tenant->status,
                        ], 403);
                    }

                    app(TenantContext::class)->setTenantId($tenant->id);
                }
            }
        }

        return $next($request);
    }
}
