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

// Paths that should redirect to home if already authenticated
const AUTH_PATHS = ['/login', '/register'];

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

  // Check if user is authenticated by looking for auth-storage cookie
  // Note: We can't access localStorage in middleware (server-side only)
  // Client-side auth checks are handled by ProtectedRoute component
  const authCookie = request.cookies.get('auth-storage');
  const isAuthenticated = !!authCookie;

  // Check if the path is an auth page (login/register)
  const isAuthPath = AUTH_PATHS.some(path =>
    pathname.startsWith(path)
  );

  // Redirect authenticated users away from auth pages
  if (isAuthPath && isAuthenticated) {
    return NextResponse.redirect(new URL('/', request.url));
  }

  // Check if the path is exactly /projects
  if (pathname === '/projects') {
    // Check if the request accepts HTML (browser navigation)
    const acceptHeader = request.headers.get('accept') || '';
    if (acceptHeader.includes('text/html')) {
      // Redirect to home page
      return NextResponse.redirect(new URL('/', request.url));
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/projects',
    '/login',
    '/register',
  ],
};