// Server-only auth helpers. These read the JWT from the httpOnly cookie
// and resolve the current user. Route handlers and server components
// call these instead of duplicating cookie/JWT logic everywhere.

import { cookies } from 'next/headers';
import { verifyToken, AppJwtPayload } from './jwt';

export const AUTH_COOKIE = 'portal_token';

export async function getCurrentUser(): Promise<AppJwtPayload | null> {
  const token = cookies().get(AUTH_COOKIE)?.value;
  if (!token) return null;
  return await verifyToken(token);
}

export async function requireAuth(): Promise<AppJwtPayload> {
  const user = await getCurrentUser();
  if (!user) {
    throw new HttpError(401, 'Authentication required');
  }
  return user;
}

export async function requireAdmin(): Promise<AppJwtPayload> {
  const user = await requireAuth();
  if (user.role !== 'ADMIN') {
    throw new HttpError(403, 'Admin access required');
  }
  return user;
}

// Custom error so route handlers can catch it and convert to JSON responses.
// Keeps controllers thin: they just throw, the handler maps to status codes.
export class HttpError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = 'HttpError';
  }
}
