import { getSession } from "../lib/neo4j.js";
const OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
const EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";
async function computeEmbedding(text) {
    try {
        const res = await fetch(`${OLLAMA_URL}/api/embed`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ model: EMBED_MODEL, input: text }),
        });
        if (!res.ok)
            return [];
        const data = (await res.json());
        return data.embeddings[0] ?? [];
    }
    catch {
        // Non-fatal: contact is created without embedding, reindex can fix later
        return [];
    }
}
export async function contactCreate(params) {
    const { givenName, familyName, email, telephone, jobTitle, source, status = "waitlist", accountId, } = params;
    const normalizedEmail = email?.toLowerCase().trim();
    const normalizedPhone = telephone?.trim();
    if (!normalizedEmail && !normalizedPhone) {
        throw new Error("At least one of email or telephone is required");
    }
    const session = getSession();
    try {
        // Dedup: check for existing contact by whichever identifiers are provided (OR logic)
        const dedupConditions = [];
        const dedupParams = { accountId };
        if (normalizedEmail) {
            dedupConditions.push("p.email = $email");
            dedupParams.email = normalizedEmail;
        }
        if (normalizedPhone) {
            dedupConditions.push("p.telephone = $telephone");
            dedupParams.telephone = normalizedPhone;
        }
        const existing = await session.run(`MATCH (p:Person {accountId: $accountId})
       WHERE ${dedupConditions.join(" OR ")}
       RETURN elementId(p) AS nodeId, p.email AS email, p.telephone AS telephone`, dedupParams);
        if (existing.records.length > 0) {
            const matchedEmail = existing.records[0].get("email");
            const matchedPhone = existing.records[0].get("telephone");
            const matchedIdentifier = matchedEmail ?? matchedPhone ?? "unknown";
            return {
                nodeId: existing.records[0].get("nodeId"),
                identifier: matchedIdentifier,
                created: false,
                alreadyExists: true,
            };
        }
        // Create new Person node (schema:Person)
        const props = {
            givenName,
            source,
            status,
            accountId,
            createdOn: new Date().toISOString(),
        };
        if (normalizedEmail)
            props.email = normalizedEmail;
        if (normalizedPhone)
            props.telephone = normalizedPhone;
        if (familyName)
            props.familyName = familyName;
        if (jobTitle)
            props.jobTitle = jobTitle;
        // Compute embedding for vector search — use whichever identifier is available
        const identifierText = normalizedEmail
            ? `<${normalizedEmail}>`
            : normalizedPhone ?? "";
        const textForEmbedding = `Person: ${givenName}${familyName ? ` ${familyName}` : ""} ${identifierText} source: ${source} status: ${status}`;
        const embedding = await computeEmbedding(textForEmbedding);
        if (embedding.length > 0) {
            props.embedding = embedding;
        }
        const result = await session.run(`CREATE (p:Person $props) RETURN elementId(p) AS nodeId`, { props });
        const primaryIdentifier = normalizedEmail ?? normalizedPhone ?? "unknown";
        return {
            nodeId: result.records[0].get("nodeId"),
            identifier: primaryIdentifier,
            created: true,
            alreadyExists: false,
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=contact-create.js.map