import { NextRequest, NextResponse } from 'next/server';
import { AUTH_CONFIG } from './lib/auth-config';

/**
 * Edge middleware — protects the authenticated zone of the site by checking
 * for the access-token cookie. Token validity is verified by the backend on
 * each API call; this is just a defence-in-depth redirect so unauthenticated
 * visitors don't even see the dashboard chrome.
 *
 * Why not jwt-verify in the middleware? The Edge runtime can't run the
 * Node argon2/jsonwebtoken modules cheaply. Trust + verify pattern:
 *   - middleware: cheap cookie presence check
 *   - backend: full JWT signature + expiry verification
 */

const PROTECTED_PREFIXES = [
  '/dashboard',
  '/emr',
  '/doctors',
  '/appointments',
  '/call',
  '/triage',
  '/prescriptions',
  '/notifications',
  '/family',
  '/profile',
  '/settings',
];
const AUTH_ONLY_PREFIXES = ['/login', '/signup'];

export function middleware(req: NextRequest): NextResponse {
  const { pathname } = req.nextUrl;
  const hasToken = !!req.cookies.get(AUTH_CONFIG.cookies.accessToken)?.value;

  const isProtected = PROTECTED_PREFIXES.some((p) => pathname.startsWith(p));
  const isAuthOnly = AUTH_ONLY_PREFIXES.some((p) => pathname.startsWith(p));

  if (isProtected && !hasToken) {
    const url = req.nextUrl.clone();
    url.pathname = AUTH_CONFIG.loginPath;
    url.searchParams.set('next', pathname);
    return NextResponse.redirect(url);
  }

  if (isAuthOnly && hasToken) {
    const url = req.nextUrl.clone();
    url.pathname = AUTH_CONFIG.dashboardPath;
    url.search = '';
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    /*
     * Match all request paths except for:
     * - api routes (we handle auth in the route handlers directly)
     * - _next static files
     * - favicon / assets
     */
    '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
};
