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;

  // 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));

  if (!isPublic) {
    const token = request.cookies.get(COOKIE_NAMES.ACCESS_TOKEN)?.value;
    if (!isTokenAlive(token)) {
      const locale = request.cookies.get('NEXT_LOCALE')?.value ?? routing.defaultLocale;
      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);
    }
  }

  // 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;

  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
  matcher: ['/((?!_next|_vercel|api|.*\\..*).*)'],
};
