import { query } from "./db.js";
export async function isActiveMember(roomId, userId, appId) {
    return (await membershipState(roomId, userId, appId)) !== "none";
}
export async function membershipState(roomId, userId, appId) {
    const res = await query(`SELECT r.archived_at
       FROM room_members m
       JOIN rooms r ON r.id = m.room_id
      WHERE m.room_id = $1
        AND m.user_id = $2
        AND m.removed_at IS NULL
        AND r.app_id = $3
      LIMIT 1`, [roomId, userId, appId]);
    const row = res.rows[0];
    if (!row)
        return "none";
    return row.archived_at ? "archived" : "open";
}
export async function sharesRoomWith(callerUserId, candidateUserIds, appId) {
    if (candidateUserIds.length === 0)
        return [];
    const res = await query(`SELECT DISTINCT other.user_id
       FROM room_members mine
       JOIN room_members other ON other.room_id = mine.room_id
       JOIN rooms r            ON r.id = mine.room_id
      WHERE mine.user_id = $1
        AND mine.removed_at IS NULL
        AND other.user_id = ANY($2::uuid[])
        AND other.removed_at IS NULL
        AND r.app_id = $3`, [callerUserId, candidateUserIds, appId]);
    return res.rows.map((row) => row.user_id);
}
export async function activeMembers(roomId, appId) {
    const res = await query(`SELECT m.user_id
       FROM room_members m
       JOIN rooms r ON r.id = m.room_id
      WHERE m.room_id = $1 AND m.removed_at IS NULL AND r.app_id = $2`, [roomId, appId]);
    return res.rows.map((row) => row.user_id);
}
