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

const PROTECTED_PREFIXES = [
  '/dashboard',
  '/appointments',
  '/prescriptions',
  '/notifications',
  '/schedule',
  '/profile',
  '/documents',
  '/devices',
  '/earnings',
  '/feedback',
  '/patients',
];
const AUTH_ONLY_PREFIXES = ['/login'];
const FORCE_PASSWORD_PATH = '/force-password-change';

export function middleware(req: NextRequest): NextResponse {
  const { pathname } = req.nextUrl;
  const hasToken = !!req.cookies.get(AUTH_CONFIG.cookies.accessToken)?.value;
  const rawUser = req.cookies.get(AUTH_CONFIG.cookies.user)?.value;
  const mustChangePassword = rawUser ? parseMustChangePassword(rawUser) : false;
  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 = mustChangePassword ? FORCE_PASSWORD_PATH : AUTH_CONFIG.dashboardPath;
    url.search = '';
    return NextResponse.redirect(url);
  }
  if (hasToken && mustChangePassword && pathname !== FORCE_PASSWORD_PATH) {
    const url = req.nextUrl.clone();
    url.pathname = FORCE_PASSWORD_PATH;
    url.search = '';
    return NextResponse.redirect(url);
  }
  if (hasToken && !mustChangePassword && pathname === FORCE_PASSWORD_PATH) {
    const url = req.nextUrl.clone();
    url.pathname = AUTH_CONFIG.dashboardPath;
    url.search = '';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

function parseMustChangePassword(rawUser: string): boolean {
  try {
    const parsed = JSON.parse(rawUser) as { mustChangePassword?: unknown };
    return parsed.mustChangePassword === true;
  } catch {
    return false;
  }
}

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)',
  ],
};
