import { NextResponse } from "next/server"
import type { NextRequest } from "next/server"

const PUBLIC_FILE = /\.(.*)$/
const SESSION_COOKIE = "painel_smtp_session"

export function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl

  // Libera rotas/arquivos públicos e TODA API (senão /api/auth/login vira 307)
  if (
    pathname.startsWith("/api") ||
    pathname.startsWith("/_next") ||
    pathname === "/favicon.ico" ||
    PUBLIC_FILE.test(pathname) ||
    pathname.startsWith("/login")
  ) {
    return NextResponse.next()
  }

  // Protege o app
  const hasSessionCookie = req.cookies.get(SESSION_COOKIE)?.value
  if (!hasSessionCookie) {
    const url = req.nextUrl.clone()
    url.pathname = "/login"
    return NextResponse.redirect(url)
  }

  return NextResponse.next()
}

export const config = {
  // Aplica middleware em tudo, EXCETO:
  // - /api/*
  // - arquivos estáticos do Next e imagens
  // - favicon
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
}
