import { getSession } from "../lib/neo4j.js";
import { computeEmbedding } from "../lib/embeddings.js";
export async function projectUpdate(params) {
    const { projectId, accountId, phase, tier, targetDate, clientRef, note, status } = params;
    const session = getSession();
    try {
        // Fetch current project
        const existing = await session.run(`MATCH (p:Project {taskId: $projectId, accountId: $accountId})
       RETURN p.name AS name, p.description AS description, p.notes AS notes,
              p.phase AS phase, p.tier AS tier, p.status AS status`, { projectId, accountId });
        if (existing.records.length === 0) {
            throw new Error(`ProjectNotFound: ${projectId}`);
        }
        const rec = existing.records[0];
        const currentName = rec.get("name");
        const currentDescription = rec.get("description");
        const currentNotes = rec.get("notes") ?? "";
        const currentPhase = rec.get("phase");
        const currentTier = rec.get("tier");
        const currentStatus = rec.get("status");
        const setClauses = ["p.updatedAt = $updatedAt"];
        const queryParams = {
            projectId,
            accountId,
            updatedAt: new Date().toISOString(),
        };
        const fieldsUpdated = [];
        let newNotes = currentNotes;
        const timestamp = new Date().toISOString().slice(0, 16).replace("T", " ");
        // Phase transition — auto-append lifecycle note
        let phaseChanged;
        if (phase && phase !== currentPhase) {
            setClauses.push("p.phase = $phase");
            queryParams.phase = phase;
            fieldsUpdated.push("phase");
            phaseChanged = { from: currentPhase, to: phase };
            const phaseSummary = note ?? "Phase transition";
            const phaseNote = `[${timestamp}] [PROJECT:PHASE] ${phase} — ${phaseSummary}`;
            newNotes = newNotes ? `${newNotes}\n${phaseNote}` : phaseNote;
        }
        // Append explicit note (separate from phase note)
        if (note && !phaseChanged) {
            const noteEntry = `[${timestamp}] ${note}`;
            newNotes = newNotes ? `${newNotes}\n${noteEntry}` : noteEntry;
        }
        if (tier) {
            setClauses.push("p.tier = $tier");
            queryParams.tier = tier;
            fieldsUpdated.push("tier");
        }
        if (targetDate) {
            setClauses.push("p.targetDate = $targetDate");
            queryParams.targetDate = targetDate;
            fieldsUpdated.push("targetDate");
        }
        if (clientRef) {
            setClauses.push("p.clientRef = $clientRef");
            queryParams.clientRef = clientRef;
            fieldsUpdated.push("clientRef");
        }
        if (status) {
            setClauses.push("p.status = $status");
            queryParams.status = status;
            fieldsUpdated.push("status");
        }
        // Always update notes (may have changed via phase note or explicit note)
        setClauses.push("p.notes = $notes");
        queryParams.notes = newNotes;
        // Re-embed with updated values
        const newTier = tier ?? currentTier;
        const newStatus = status ?? currentStatus;
        const embeddingText = `Project: ${currentName} — ${currentDescription} tier: ${newTier} status: ${newStatus}${newNotes ? " " + newNotes : ""}`;
        const embedding = await computeEmbedding(embeddingText);
        if (embedding.length > 0) {
            setClauses.push("p.embedding = $embedding");
            queryParams.embedding = embedding;
        }
        await session.run(`MATCH (p:Project {taskId: $projectId, accountId: $accountId})
       SET ${setClauses.join(", ")}`, queryParams);
        // Log
        if (phaseChanged) {
            console.error(`project-update: ${projectId} phase=${phaseChanged.from}→${phaseChanged.to}`);
        }
        else {
            console.error(`project-update: ${projectId} updated ${fieldsUpdated.length > 0 ? fieldsUpdated.join(", ") : "notes"}`);
        }
        return { phaseChanged, fieldsUpdated };
    }
    catch (err) {
        if (err instanceof Error && err.message.startsWith("ProjectNotFound:")) {
            console.error(`project-update: failed — ${err.message}`);
        }
        else {
            console.error(`project-update: failed — ${err instanceof Error ? err.message : String(err)}`);
        }
        throw err;
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=project-update.js.map