<?php

namespace App\Modules\Admin\Tenancy\Middleware;

use App\Models\User;
use App\Modules\Admin\Tenancy\Support\TenantLifecycleState;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class EnsureTenantLifecycleAllowsAccess
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        if ($user === null || $user->isAdmin()) {
            return $next($request);
        }

        if (Session::has('support_impersonation')) {
            return $next($request);
        }

        if ($this->allowsImpersonationEnd($request)) {
            return $next($request);
        }

        $tenant = $user->tenant;
        if ($tenant === null) {
            return $next($request);
        }

        $state = (string) $tenant->lifecycle_state;
        if (! in_array($state, [TenantLifecycleState::SUSPENDED, TenantLifecycleState::ARCHIVED], true)) {
            return $next($request);
        }

        if ($request->expectsJson()) {
            return response()->json(['message' => __('tenant_lifecycle.blocked')], 403);
        }

        return response()->view('pages.tenant.lifecycle-blocked', ['state' => $state], 403);
    }

    private function allowsImpersonationEnd(Request $request): bool
    {
        return $request->routeIs('support.impersonation.end')
            && $request->isMethod('post');
    }
}
