import createMiddleware from 'next-intl/middleware';
import {routing} from './i18n/routing';
import { NextRequest, NextResponse } from 'next/server';

const handleI18n = createMiddleware(routing);

export function proxy(request: NextRequest) {
  const response = handleI18n(request);

  // If next-intl redirects (e.g. for locale prefix), let it pass
  if (response.status >= 300 && response.status < 400) {
    return response;
  }

  // Auth check logic
  const sessionCookie = request.cookies.get("better-auth.session_token");
  const { pathname } = request.nextUrl;

  // Check if accessing dashboard
  // Matches /dashboard, /en/dashboard, /id/dashboard, etc.
  const isDashboardRoute = pathname === '/dashboard' || 
                           pathname.startsWith('/dashboard/') || 
                           routing.locales.some(locale => pathname.startsWith(`/${locale}/dashboard`));

  if (isDashboardRoute && !sessionCookie) {
    // Extract locale from path to maintain consistency, fallback to default
    const segments = pathname.split('/');
    const potentialLocale = segments[1];
    const locale = routing.locales.includes(potentialLocale as any) 
      ? potentialLocale 
      : routing.defaultLocale;

    return NextResponse.redirect(new URL(`/${locale}/auth/signin`, request.url));
  }

  return response;
}

export const config = {
  // Match all pathnames except for
  // - … if they start with `/api`, `/trpc`, `/_next` or `/_vercel`
  // - … the ones containing a dot (e.g. `favicon.ico`)
  matcher: ['/((?!api|trpc|_next|_vercel|.*\\..*).*)']
};
