import {
  convexAuthNextjsMiddleware,
  createRouteMatcher,
  nextjsMiddlewareRedirect,
} from '@convex-dev/auth/nextjs/server';

const isAuthRoute = createRouteMatcher(['/sign-in', '/forgot-password']);
const isProtectedRoute = createRouteMatcher([
  '/dashboard(.*)',
  '/spoons(.*)',
  '/updates(.*)',
  '/agents(.*)',
  '/threads(.*)',
  '/github(.*)',
  '/settings(.*)',
  '/profile(.*)',
]);

export default convexAuthNextjsMiddleware(
  async (request, { convexAuth }) => {
    const isAuthenticated = await convexAuth.isAuthenticated();
    if (isAuthRoute(request) && isAuthenticated) {
      return nextjsMiddlewareRedirect(request, '/dashboard');
    }
    if (isProtectedRoute(request) && !isAuthenticated) {
      return nextjsMiddlewareRedirect(request, '/sign-in');
    }
  },
  { cookieConfig: { maxAge: 60 * 60 * 24 * 30 } },
);

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