import { getDB } from '../db.js';
import { createLogger } from '../diagnostics/logger.js';
const dbLogger = createLogger('db');
export class ModelNotAvailableError extends Error {
    model;
    constructor(model) {
        super(`Model "${model}" is not available in the Prisma schema.`);
        this.model = model;
    }
}
/**
 * Returns the Prisma client wrapped in a Proxy that throws a typed
 * {@link ModelNotAvailableError} when a route touches a model that isn't in
 * the consumer's schema (instead of an opaque `undefined` TypeError). When
 * the DB client itself can't be obtained, every model access throws so each
 * route's error handler can translate it into a 503-style response.
 */
export function guardedDb() {
    let d;
    try {
        d = getDB();
    }
    catch (err) {
        dbLogger.error('Failed to obtain database client', {
            error: err instanceof Error ? err.message : String(err),
        });
        return new Proxy({}, {
            get(_target, prop) {
                if (typeof prop !== 'string' || prop.startsWith('$') || prop === 'then')
                    return undefined;
                return new Proxy({}, {
                    get() {
                        throw new ModelNotAvailableError(String(prop));
                    },
                });
            },
        });
    }
    return new Proxy(d, {
        get(target, prop) {
            if (typeof prop !== 'string')
                return Reflect.get(target, prop);
            if (prop.startsWith('$') || prop === 'then')
                return Reflect.get(target, prop);
            let val;
            try {
                val = target[prop];
            }
            catch {
                val = undefined;
            }
            if (val !== undefined && val !== null)
                return val;
            return new Proxy({}, {
                get() {
                    throw new ModelNotAvailableError(String(prop));
                },
            });
        },
    });
}
//# sourceMappingURL=guarded-db.js.map