import { writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { getSession } from "../lib/neo4j.js";
import { assertUUID, readMeta, attachmentDir, } from "../lib/attachments.js";
export async function memoryRenameAttachment(params) {
    const { accountId, attachmentId, newFilename } = params;
    assertUUID(attachmentId, "attachmentId");
    if (!newFilename || newFilename.trim().length === 0) {
        throw new Error("newFilename must not be empty.");
    }
    const trimmedName = newFilename.trim();
    const t0 = Date.now();
    const tag = attachmentId.slice(0, 8);
    const log = (stage, detail) => console.error(`[memory-rename-attachment] [${tag}] ${stage}${detail ? ` — ${detail}` : ""} (${Date.now() - t0}ms)`);
    log("start", `→ "${trimmedName}"`);
    const meta = await readMeta(accountId, attachmentId);
    if (!meta) {
        throw new Error(`Attachment "${attachmentId}" not found. ` +
            `No metadata file exists for this attachment in this account.`);
    }
    const oldFilename = meta.filename;
    if (oldFilename === trimmedName) {
        log("no-op", "filename unchanged");
        return { attachmentId, oldFilename, newFilename: trimmedName, graphUpdated: false };
    }
    // Update Neo4j first — if this fails, nothing has changed on disk
    let graphUpdated = false;
    const session = getSession();
    try {
        const result = await session.run(`MATCH (d:KnowledgeDocument { attachmentId: $attachmentId, accountId: $accountId })
       SET d.name = $newFilename, d.updatedAt = $updatedAt
       RETURN count(d) AS updated`, {
            attachmentId,
            accountId,
            newFilename: trimmedName,
            updatedAt: new Date().toISOString(),
        });
        graphUpdated =
            (result.records[0]?.get("updated")?.toNumber?.() ?? 0) > 0;
        if (graphUpdated) {
            log("graph-updated", `"${oldFilename}" → "${trimmedName}"`);
        }
        else {
            log("graph-skipped", "no KnowledgeDocument node for this attachment");
        }
    }
    finally {
        await session.close();
    }
    // Update .meta.json
    const updatedMeta = { ...meta, filename: trimmedName };
    const metaPath = resolve(attachmentDir(accountId, attachmentId), `${attachmentId}.meta.json`);
    await writeFile(metaPath, JSON.stringify(updatedMeta, null, 2));
    log("meta-updated");
    log("complete", `"${oldFilename}" → "${trimmedName}"`);
    return {
        attachmentId,
        oldFilename,
        newFilename: trimmedName,
        graphUpdated,
    };
}
//# sourceMappingURL=memory-rename-attachment.js.map