import { getSession } from "../lib/neo4j.js";
import { notTrashed } from "../../../../../lib/graph-trash/dist/index.js";
export async function groupManage(params) {
    const { groupSlug, action, participant, accountId } = params;
    const session = getSession();
    try {
        // Find the group (skip trashed — they should behave as not-found).
        const groupResult = await session.run(`MATCH (c:Conversation {groupSlug: $groupSlug, accountId: $accountId, type: 'group'})
       WHERE ${notTrashed("c")}
       RETURN c.sessionId AS sessionId, c.groupName AS groupName`, { groupSlug, accountId });
        const record = groupResult.records[0];
        if (!record) {
            throw new Error(`Group not found: ${groupSlug}`);
        }
        const sessionId = record.get("sessionId");
        const groupName = record.get("groupName");
        if (action === "add") {
            if (!participant)
                throw new Error("participant is required for add action");
            const addResult = await session.run(`MATCH (p:Person {accountId: $accountId})
         WHERE (p.givenName + COALESCE(' ' + p.familyName, '') = $participant
            OR p.email = $participant
            OR p.telephone = $participant)
           AND ${notTrashed("p")}
         WITH p LIMIT 1
         MATCH (c:Conversation {sessionId: $sessionId})
         MERGE (p)-[r:PARTICIPATES_IN]->(c)
         ON CREATE SET r.joinedAt = datetime(), r.displayName = p.givenName
         RETURN p.givenName AS name`, { accountId, participant, sessionId });
            const name = addResult.records[0]?.get("name");
            if (!name) {
                throw new Error(`Contact not found: ${participant}`);
            }
            console.error(`[group] participant-added id=${sessionId.slice(0, 8)}… name=${name}`);
        }
        else if (action === "remove") {
            if (!participant)
                throw new Error("participant is required for remove action");
            const removeResult = await session.run(`MATCH (p:Person {accountId: $accountId})-[r:PARTICIPATES_IN]->(c:Conversation {sessionId: $sessionId})
         WHERE (p.givenName + COALESCE(' ' + p.familyName, '') = $participant
            OR p.email = $participant
            OR p.telephone = $participant)
           AND ${notTrashed("p")}
         DELETE r
         RETURN count(r) AS removed`, { accountId, participant, sessionId });
            const removed = removeResult.records[0]?.get("removed")?.toNumber?.() ?? 0;
            if (removed === 0) {
                throw new Error(`Participant not found in group: ${participant}`);
            }
            console.error(`[group] participant-removed id=${sessionId.slice(0, 8)}… name=${participant}`);
        }
        // Always return current participants. Trashed persons are filtered out
        // so the group view reflects active membership only — the PARTICIPATES_IN
        // edge survives soft-delete, but the participant list shouldn't surface
        // them.
        const listResult = await session.run(`MATCH (p:Person)-[r:PARTICIPATES_IN]->(c:Conversation {sessionId: $sessionId})
       WHERE ${notTrashed("p")}
       RETURN r.displayName AS displayName
       ORDER BY r.joinedAt ASC`, { sessionId });
        const participants = listResult.records.map((r) => r.get("displayName"));
        return {
            action,
            groupName,
            participant: participant ?? undefined,
            participants,
        };
    }
    finally {
        await session.close();
    }
}
//# sourceMappingURL=group-manage.js.map