import createMiddleware from 'next-intl/middleware';
import { type NextRequest, NextResponse } from 'next/server';
import { routing } from './src/i18n/routing';
import { COOKIE_NAMES } from './src/lib/cookies';
import { isTokenAlive } from './src/lib/auth/token';
import { HEADER_NAMES, PUBLIC_PATHS, RETURN_URL_PARAM, ROUTES } from './src/constants';

const intlMiddleware = createMiddleware(routing);

export default function middleware(request: NextRequest) {
  const i18nResponse = intlMiddleware(request);

  // If next-intl is issuing a locale normalization redirect, let it through immediately
  if (i18nResponse.status === 307 || i18nResponse.status === 308) {
    return i18nResponse;
  }

  const { pathname } = request.nextUrl;

  // Detect locale from the normalized URL (next-intl always puts it at position 1)
  const locale = routing.locales.find(
    (l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`),
  ) ?? routing.defaultLocale;

  // Strip the locale segment to get the actual path (e.g. /fa/login → /login)
  const pathWithoutLocale = '/' + pathname.split('/').slice(2).join('/');

  const isPublic = PUBLIC_PATHS.some((p) => pathWithoutLocale.startsWith(p));
  const isAuthenticated = isTokenAlive(request.cookies.get(COOKIE_NAMES.ACCESS_TOKEN)?.value);

  // Guest front door (ui-phase-13): an unauthenticated hit on the exact root is REWRITTEN — never
  // redirected — to the public landing, so the URL/SEO canonical stays '/'. Exact match only:
  // never add ROUTES.HOME ('/') to PUBLIC_PATHS itself, whose `startsWith` check below would
  // otherwise silently un-gate every route (§ the routes.ts comment on PUBLIC_PATHS).
  if (!isAuthenticated && pathWithoutLocale === ROUTES.HOME) {
    return NextResponse.rewrite(new URL(`/${locale}${ROUTES.WELCOME}`, request.url));
  }

  // A signed-in visitor landing on the marketing page directly gets their real home instead.
  if (isAuthenticated && pathWithoutLocale === ROUTES.WELCOME) {
    return NextResponse.redirect(new URL(`/${locale}${ROUTES.HOME}`, request.url));
  }

  if (!isPublic && !isAuthenticated) {
    const loginUrl = new URL(`/${locale}${ROUTES.LOGIN}`, request.url);
    // Carry the attempted (locale-stripped) destination so a deep link — an SMS booking link, a
    // shared nurse profile — survives the round trip through login instead of dumping the user
    // on their role home. Validated same-origin + role-permitting on the way back out
    // (resolvePostLoginDestination in services/auth/routing.ts); '/' is the default anyway.
    const next = pathWithoutLocale + request.nextUrl.search;
    if (next && next !== '/') {
      loginUrl.searchParams.set(RETURN_URL_PARAM, next);
    }
    return NextResponse.redirect(loginUrl);
  }

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set(HEADER_NAMES.LOCALE, locale);

  const response = NextResponse.next({ request: { headers: requestHeaders } });

  // Preserve response headers set by next-intl (e.g. Link: alternate hreflang)
  i18nResponse.headers.forEach((value, key) => {
    response.headers.set(key, value);
  });

  return response;
}

export const config = {
  // Match all pathnames except internal Next.js paths, API routes, and static files. The bare
  // root '/' is listed explicitly alongside the catch-all regex — Next's matcher does not
  // reliably invoke middleware for the literal root path through the negative-lookahead pattern
  // alone (verified empirically in this Next 16/Turbopack build: '/' skipped middleware entirely
  // and 404'd, while every other path matched fine). This is load-bearing for ui-phase-13's
  // guest-front-door rewrite, which only fires on an exact '/' match.
  matcher: ['/', '/((?!_next|_vercel|api|.*\\..*).*)'],
};
