import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; export async function middleware(request: NextRequest) { const hostname = request.headers.get('host') || ''; const url = request.nextUrl; const apiBase = process.env.API_INTERNAL_URL || 'http://backend:8080'; // Extrair subdomínio const subdomain = hostname.split('.')[0]; // Validar subdomínio de agência ({subdomain}.localhost) if (hostname.includes('.')) { try { const res = await fetch(`${apiBase}/api/tenant/check?subdomain=${subdomain}`); if (!res.ok) { const baseHost = hostname.split('.').slice(1).join('.') || hostname; const redirectUrl = new URL(url.toString()); redirectUrl.hostname = baseHost; redirectUrl.pathname = '/'; return NextResponse.redirect(redirectUrl); } } catch (err) { const baseHost = hostname.split('.').slice(1).join('.') || hostname; const redirectUrl = new URL(url.toString()); redirectUrl.hostname = baseHost; redirectUrl.pathname = '/'; return NextResponse.redirect(redirectUrl); } } // Permitir acesso normal return NextResponse.next(); } export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], };