/**
 * Defensive Prisma connection-pool default.
 *
 * Prisma's MySQL pool defaults to `num_physical_cpus * 2 + 1` connections.
 * On a small VPS (2–4 cores) that is 5–9 connections — which the web process
 * can starve under concurrent analytics aggregation + outbox drain + SSE
 * fan-out, queueing queries behind `pool_timeout` and surfacing as slow
 * dashboards. The pool size is controlled by the `connection_limit` query
 * param on DATABASE_URL (Prisma reads it from the URL; there is no client
 * constructor option for it on MySQL).
 *
 * Policy: the OPERATOR is authoritative. If DATABASE_URL already carries a
 * `connection_limit`, we never touch it. Only when it's absent do we append a
 * conservative default so a fresh deploy doesn't silently run on the
 * cpu-derived value. See .env.example for the web-vs-worker sizing guidance.
 */

/**
 * Return DATABASE_URL with a `connection_limit` applied iff the operator has
 * not set one. Never overrides an explicit value. Defensive: if the input is
 * absent or not a parseable URL, it's returned unchanged so startup behaves
 * exactly as before (env validation owns the "missing/invalid" error path).
 */
export function resolveDatabaseUrl(
    rawUrl: string | undefined,
    defaultLimit: number,
): string | undefined {
    if (!rawUrl) return rawUrl;

    let url: URL;
    try {
        url = new URL(rawUrl);
    } catch {
        return rawUrl;
    }

    if (url.searchParams.has('connection_limit')) return rawUrl;

    url.searchParams.set('connection_limit', String(defaultLimit));
    return url.toString();
}
