import createMiddleware from 'next-intl/middleware';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import {
  getLocaleFromPathname,
  routing,
  stripLocaleFromPathname,
} from './i18n/routing';
import { hasUsableAccessToken } from './lib/auth/accessToken';

const handleI18nRouting = createMiddleware(routing);

/** Routes that must work without an existing session (first-time invitees). */
const publicRoutes = [
  '/',
  '/login',
  '/register',
  '/terms',
  '/privacy',
  '/forgot-password',
  '/accept-invite',
  '/accept-organization-invite',
];

function isRedirectResponse(response: Response): boolean {
  return response.status >= 300 && response.status < 400;
}

export function proxy(request: NextRequest) {
  const intlResponse = handleI18nRouting(request);

  if (isRedirectResponse(intlResponse)) {
    return intlResponse;
  }

  const { pathname } = request.nextUrl;
  const pathWithoutLocale = stripLocaleFromPathname(pathname);
  const locale = getLocaleFromPathname(pathname);
  const token = request.cookies.get('accessToken')?.value;
  const isAuthenticated = hasUsableAccessToken(token);

  if (isAuthenticated && pathWithoutLocale === '/') {
    return NextResponse.redirect(new URL(`/${locale}/today`, request.url));
  }

  if (publicRoutes.includes(pathWithoutLocale)) {
    return intlResponse;
  }

  if (!isAuthenticated) {
    if (pathWithoutLocale === '/login') {
      return intlResponse;
    }

    const loginUrl = new URL(`/${locale}/login`, request.url);
    loginUrl.searchParams.set('from', pathname);
    return NextResponse.redirect(loginUrl);
  }

  return intlResponse;
}

export const config = {
  matcher: [
    '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
};
