// // Edge middleware. Verifies the JWT cookie on protected routes before
// // the request reaches a route handler or page. Using `jose` here is
// // what allows us to verify on Edge instead of pushing every check
// // into per-route logic.

// import { NextRequest, NextResponse } from 'next/server';
// import { verifyToken } from '@/lib/auth/jwt';
// import { AUTH_COOKIE } from '@/lib/auth/session';

// const PUBLIC_PATHS = [
//   '/login',
//   '/api/auth/login',
// ];

// function isPublic(pathname: string): boolean {
//   return PUBLIC_PATHS.some((p) => pathname === p || pathname.startsWith(p + '/'));
// }

// export async function middleware(req: NextRequest) {
//   const { pathname } = req.nextUrl;

//   if (isPublic(pathname)) return NextResponse.next();

//   const token = req.cookies.get(AUTH_COOKIE)?.value;
//   const payload = token ? await verifyToken(token) : null;

//   if (!payload) {
//     // For API calls return 401 JSON; for pages, redirect to login
//     if (pathname.startsWith('/api/')) {
//       return NextResponse.json({ ok: false, error: 'Authentication required' }, { status: 401 });
//     }
//     const url = req.nextUrl.clone();
//     url.pathname = '/login';
//     url.searchParams.set('next', pathname);
//     return NextResponse.redirect(url);
//   }

//   // Admin gate
//   const isAdminRoute = pathname.startsWith('/admin') || pathname.startsWith('/api/admin') || pathname.startsWith('/api/categories/admin');
//   if (isAdminRoute && payload.role !== 'ADMIN') {
//     if (pathname.startsWith('/api/')) {
//       return NextResponse.json({ ok: false, error: 'Admin access required' }, { status: 403 });
//     }
//     return NextResponse.redirect(new URL('/dashboard', req.url));
//   }

//   return NextResponse.next();
// }

// export const config = {
//   // Run on everything except static assets and the public uploads folder
//   matcher: ['/((?!_next/static|_next/image|favicon.ico|uploads).*)'],
// };
import { NextRequest, NextResponse } from 'next/server';
import { verifyToken } from '@/lib/auth/jwt';
import { AUTH_COOKIE } from '@/lib/auth/session';

const PUBLIC_PATHS = [
  '/login',
  '/api/auth/login',
];

function isPublic(pathname: string): boolean {
  return PUBLIC_PATHS.some(
    (p) => pathname === p || pathname.startsWith(p + '/')
  );
}

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

  // Public routes
  if (isPublic(pathname)) {
    return NextResponse.next();
  }

  const token = req.cookies.get(AUTH_COOKIE)?.value;
  const payload = token ? await verifyToken(token) : null;

  // Not authenticated
  if (!payload) {
    if (pathname.startsWith('/api/')) {
      return NextResponse.json(
        { ok: false, error: 'Authentication required' },
        { status: 401 }
      );
    }

    const url = req.nextUrl.clone();
    url.pathname = '/login';
    url.searchParams.set('next', pathname);

    return NextResponse.redirect(url);
  }

  // Admin-only routes
  const isAdminRoute =
    pathname.startsWith('/admin') ||
    pathname.startsWith('/api/admin') ||
    pathname.startsWith('/api/categories/admin');

  if (isAdminRoute && payload.role !== 'ADMIN') {
    if (pathname.startsWith('/api/')) {
      return NextResponse.json(
        { ok: false, error: 'Admin access required' },
        { status: 403 }
      );
    }

    return NextResponse.redirect(new URL('/dashboard', req.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
      Exclude:
      - Next internals
      - favicon
      - uploads
      - any file with extension (.png, .jpg, .svg, .css, .js, etc.)
    */
    '/((?!_next/static|_next/image|favicon.ico|uploads|.*\\..*).*)',
  ],
};