import createMiddleware from "next-intl/middleware"
import { NextRequest, NextResponse } from "next/server"

const LOCALES = ["fr", "en"]
const DEFAULT_LOCALE = "fr"

const handleI18n = createMiddleware({
  locales: LOCALES,
  defaultLocale: DEFAULT_LOCALE,
  localePrefix: "always",
})

function localeFromPath(pathname: string): string {
  const seg = pathname.split("/")[1]
  return LOCALES.includes(seg) ? seg : DEFAULT_LOCALE
}

export default function middleware(req: NextRequest) {
  const host = (req.headers.get("host") || "").toLowerCase()
  const pathname = req.nextUrl.pathname
  const locale = localeFromPath(pathname)

  // ── Domaine super-admin : gestion.acx-acremac.net ─────────────────────────
  // Seules les routes /admin/* sont autorisées. Tout le reste → /admin/login
  if (host.startsWith("gestion.")) {
    const isAdminRoute = new RegExp(`^/(${LOCALES.join("|")})/admin`).test(pathname)
    const isRoot = pathname === "/" || LOCALES.some((l) => pathname === `/${l}` || pathname === `/${l}/`)

    if (!isAdminRoute && !isRoot) {
      return NextResponse.redirect(new URL(`/${locale}/admin/login`, req.url))
    }
    return handleI18n(req)
  }

  // ── Domaine agent/client : app.acx-acremac.net ────────────────────────────
  // Bloquer l'accès aux routes /admin/*
  if (new RegExp(`^/(${LOCALES.join("|")})/admin`).test(pathname)) {
    return NextResponse.redirect(new URL(`/${locale}/login`, req.url))
  }

  return handleI18n(req)
}

export const config = {
  matcher: ["/((?!api|_next|.*\\..*).*)"],
}
