/**
 * AUDIT-2 #15.2 (2026-05-23): sanitize errors before returning them
 * to unauthenticated or low-privilege callers.
 *
 * Background: three endpoints were echoing `error.message` verbatim
 * (status route, NOC verify, NOC tokens). A Prisma P2022 leaks the
 * column name → schema disclosure. A connection ECONNREFUSED leaks
 * the DB endpoint. Generic "internal error" + a correlation ID lets
 * the operator find the full detail in server logs without telling
 * the caller anything about our internals.
 *
 * Usage:
 *
 *   try {
 *       // ... handler logic
 *   } catch (err) {
 *       const sanitized = sanitizeErrorForResponse(err, { route: '/api/status' });
 *       return NextResponse.json(sanitized.body, { status: sanitized.status });
 *   }
 *
 * Authenticated-admin endpoints should keep verbose errors — this
 * helper is for endpoints that anonymous or VIEWER-level callers can
 * hit.
 */
import crypto from 'crypto';

interface SanitizeContext {
    /** Route path for log correlation, e.g. '/api/status'. */
    route?: string;
    /** HTTP status to return. Defaults to 500. */
    status?: number;
    /** Generic message returned to the client. */
    publicMessage?: string;
}

interface SanitizedError {
    body: { success: false; error: string; correlationId: string };
    status: number;
    /** Full server-side context — log with your usual logger. */
    serverContext: { correlationId: string; route?: string; error: unknown };
}

/**
 * Replace `error.message` with a generic message + a UUID-ish
 * correlation ID. Caller MUST log `serverContext` so the operator
 * can grep for the correlation ID in production logs and find the
 * real error.
 */
export function sanitizeErrorForResponse(err: unknown, ctx: SanitizeContext = {}): SanitizedError {
    const correlationId = crypto.randomBytes(8).toString('hex');
    const status = ctx.status ?? 500;
    const publicMessage = ctx.publicMessage ?? 'Internal error';
    return {
        body: {
            success: false,
            error: `${publicMessage}. Reference: ${correlationId}`,
            correlationId,
        },
        status,
        serverContext: {
            correlationId,
            route: ctx.route,
            error: err,
        },
    };
}
