import { withAuth } from 'next-auth/middleware';
import createMiddleware from 'next-intl/middleware';
import { NextRequest, NextResponse } from 'next/server';
import { locales, defaultLocale } from './i18n';

// Public paths that don't require authentication
const publicPages = ['/login', '/setup'];

// Create the next-intl middleware
const intlMiddleware = createMiddleware({
  locales,
  defaultLocale,
  localePrefix: 'always',
});

// Create the next-auth middleware
const authMiddleware = withAuth(
  // Note: This function is only invoked if authorized callback returns true
  function onSuccess(req) {
    return intlMiddleware(req);
  },
  {
    callbacks: {
      authorized: ({ token }) => token !== null,
    },
    pages: {
      signIn: '/login',
    },
  }
);

/**
 * Main middleware function
 * Handles both internationalization and authentication
 */
export default function middleware(req: NextRequest) {
  const pathname = req.nextUrl.pathname;

  // Check if the path is a public path (handle locale prefix)
  const pathnameWithoutLocale = locales.reduce(
    (path, locale) => path.replace(`/${locale}`, ''),
    pathname
  );

  const isPublicPage = publicPages.some(
    (page) => pathnameWithoutLocale === page || pathnameWithoutLocale.startsWith(`${page}/`)
  );

  // Skip auth check for public pages and just handle i18n
  if (isPublicPage) {
    return intlMiddleware(req);
  }

  // For protected pages, use auth middleware
  return (authMiddleware as (req: NextRequest) => NextResponse | Promise<NextResponse>)(req);
}

export const config = {
  // Match all paths except static files, api routes, and next internals
  matcher: ['/((?!api|_next|.*\\..*).*)'],
};
