import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const PUBLIC_FILE = /\.(.*)$/;
const locales = ['en', 'fa'];
const defaultLocale = 'en';

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;

  // Ignore public files and API routes
  if (pathname.startsWith('/api') || PUBLIC_FILE.test(pathname)) {
    return NextResponse.next();
  }

  // Check if the pathname already includes a locale
  const matchedLocale = locales.find(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
  );

  const locale = matchedLocale || defaultLocale;

  let response: NextResponse;

  // If locale is missing, redirect and set cookie
  const pathnameIsMissingLocale = !matchedLocale;
  if (pathnameIsMissingLocale) {
    response = NextResponse.redirect(
      new URL(`/${defaultLocale}${pathname}`, request.url),
    );
  } else {
    response = NextResponse.next();
  }

  // Set the locale cookie for all responses
  response.cookies.set('locale', locale, { path: '/' });

  return response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico|api).*)'],
};
