import neo4j from "neo4j-driver";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
let driver = null;
function readPassword() {
    if (process.env.NEO4J_PASSWORD)
        return process.env.NEO4J_PASSWORD;
    const passwordFile = resolve(process.env.PLATFORM_ROOT ?? resolve(import.meta.dirname, "../../../.."), "config/.neo4j-password");
    try {
        return readFileSync(passwordFile, "utf-8").trim();
    }
    catch {
        throw new Error(`Neo4j password not found. Expected at ${passwordFile} or in NEO4J_PASSWORD env var.`);
    }
}
export function getDriver() {
    if (!driver) {
        const uri = process.env.NEO4J_URI ?? "bolt://localhost:7687";
        const user = process.env.NEO4J_USER ?? "neo4j";
        const password = readPassword();
        driver = neo4j.driver(uri, neo4j.auth.basic(user, password));
    }
    return driver;
}
export function getSession() {
    return getDriver().session();
}
export async function closeDriver() {
    if (driver) {
        await driver.close();
        driver = null;
    }
}
/**
 * Fetches the user's IANA timezone from their UserProfile node.
 * Throws if the profile doesn't exist or the timezone is not set —
 * callers must not silently fall back to a default.
 */
export async function getUserTimezone(accountId) {
    const session = getSession();
    try {
        const result = await session.run(`MATCH (up:UserProfile {accountId: $accountId})
       RETURN up.timezone AS timezone`, { accountId });
        if (result.records.length === 0) {
            throw new Error(`No UserProfile found for account ${accountId.slice(0, 8)}… — cannot format locale times`);
        }
        const timezone = result.records[0].get("timezone");
        if (!timezone || timezone.trim().length === 0) {
            throw new Error(`No timezone set for account ${accountId.slice(0, 8)}… — use profile-update (memory plugin) with profileFields: { timezone: 'YOUR_IANA_TZ' } to set it`);
        }
        return timezone;
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=neo4j.js.map