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

export function middleware(request: NextRequest) {
  const token =
    request.cookies.get('next-auth.session-token')?.value ??
    request.cookies.get('__Secure-next-auth.session-token')?.value;

  const isLoggedIn = Boolean(token);

  if (request.nextUrl.pathname.startsWith('/api/')) {
    // List of public API routes that don't require authentication
    const publicApiRoutes = ['/api/auth', '/api/oauth/callback', '/api/users/', '/api/auth/password-reset', '/api/portfolios/published'];

    const isPublicApiRoute = publicApiRoutes.some((route) => request.nextUrl.pathname.startsWith(route));

    if (!isPublicApiRoute && !isLoggedIn) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
  }

  const protectedPaths = ['/dashboard', '/portfolios', '/projects', '/deployments'];
  const isProtectedRoute = protectedPaths.some((path) => request.nextUrl.pathname.startsWith(path));

  if (request.nextUrl.pathname === '/' && isLoggedIn) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  const isPublicRoute = ['/login', '/register'];
  const isPublicPath = isPublicRoute.some((path) => request.nextUrl.pathname.startsWith(path));
  if (isPublicPath && isLoggedIn) {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  if (isProtectedRoute && !isLoggedIn) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/dashboard/:path*', '/portfolios/:path*', '/projects/:path*', '/deployments/:path*', '/', '/api/:path*', '/login', '/register'],
};
