import { withAuth } from 'next-auth/middleware';
import { NextRequest, NextResponse } from 'next/server';

const authMiddleware = withAuth(
  function middleware(req: any) {
    return NextResponse.next();
  },
  {
    callbacks: {
      authorized: ({ token, req }: any) => {
        const path = req?.nextUrl?.pathname ?? '';
        if (path?.startsWith('/admin') && !path?.startsWith('/admin/login')) {
          return !!token;
        }
        return true;
      },
    },
  }
);

export default function middleware(req: NextRequest) {
  const path = req.nextUrl.pathname;

  // Skip cache headers for static assets
  if (path.startsWith('/_next/static') || path.startsWith('/images/') || path.startsWith('/favicon')) {
    return NextResponse.next();
  }

  // Admin routes: delegate to auth middleware
  if (path.startsWith('/admin')) {
    return (authMiddleware as any)(req);
  }

  // All other routes: add no-cache headers
  const response = NextResponse.next();
  response.headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
  response.headers.set('Pragma', 'no-cache');
  response.headers.set('Expires', '0');
  return response;
}

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon).*)'],
};
