// Clerk-driven auth gate. Routes under `/dashboard/*` require sign-in;
// everything else is public. Webhook routes are explicitly opt-out.
//
// Reference: https://clerk.com/docs/references/nextjs/clerk-middleware
//
// NOTE: Next.js 16.2+ deprecated `middleware.ts` in favor of `proxy.ts`
// (same file shape, just renamed). It's a warning, not an error —
// `middleware.ts` still works through Next 17. Clerk's docs still
// recommend `middleware.ts` for now; rename to `proxy.ts` when Clerk
// updates its docs.

import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';

// path-to-regexp (used by createRouteMatcher) doesn't support negative
// lookahead. Use an explicit public allowlist and protect everything else.
const isPublicRoute = createRouteMatcher([
  '/',
  '/sign-in(.*)',
  '/sign-up(.*)',
  '/api/webhooks/(.*)',
]);

export default clerkMiddleware(async (auth, req) => {
  if (!isPublicRoute(req)) {
    await auth.protect();
  }
});

export const config = {
  matcher: [
    // Skip Next.js internals and static assets unless we explicitly opt in.
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run on API routes.
    '/(api|trpc)(.*)',
  ],
};
