import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { BASE_URL } from './api/config';

export async function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const publicPaths = ['/signin', '/signup', '/error', '/not-found'];
  const isPublicPath = publicPaths.includes(pathname);
  let isAuthenticated = false;
  
  if (isPublicPath) {
    return NextResponse.next();
  }

  try {
    const response = await fetch(new URL('api/users/me/', BASE_URL), {
      headers: {
        cookie: request.headers.get('cookie') || '',
      },
    });
    if (response.ok) {
      isAuthenticated = true;
    } else if (response.status == 401) {
      isAuthenticated = false;
    }
  } catch (error) {
    console.error('Middleware auth check failed:', error);
    // Treat as unauthenticated if the API call fails
    isAuthenticated = false;
  }

  if (!isAuthenticated) {
    const loginUrl = new URL('/signin', request.url);
    loginUrl.searchParams.set('next', pathname);
    return NextResponse.redirect(loginUrl);
  }

  // If the user is authenticated and tries to access a public-only page like signin
  if (pathname.startsWith('/signin') || pathname.startsWith('/signup')) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  // Otherwise, allow the request to proceed
  return NextResponse.next();
}

export const config = {
  /*
   * Match all request paths except for the ones starting with:
   * - _next/static (static files)
   * - _next/image (image optimization files)
   * - favicon.ico (favicon file)
   * - images (image files in public)
   * - svg (svg files)
   */
  matcher: '/((?!_next/static|_next/image|favicon.ico|images|svg).*)',
}