import { query, withTransaction } from "./db.js";
export async function roomsHasData(userId) {
    const res = await query(`SELECT 1 FROM room_members WHERE user_id = $1 AND removed_at IS NULL LIMIT 1`, [userId]);
    return res.rows.length > 0;
}
export async function mergeRoomMemberships(guestUserId, targetUserId) {
    await withTransaction(async (tx) => {
        await tx.query(`UPDATE room_members t
          SET role      = CASE WHEN t.role = 'owner' OR g.role = 'owner'
                               THEN 'owner' ELSE t.role END,
              joined_at = LEAST(t.joined_at, g.joined_at),
              removed_at     = CASE WHEN t.removed_at IS NULL OR g.removed_at IS NULL
                                    THEN NULL ELSE t.removed_at END,
              removed_reason = CASE WHEN t.removed_at IS NULL OR g.removed_at IS NULL
                                    THEN NULL ELSE t.removed_reason END,
              display_name   = COALESCE(t.display_name, g.display_name)
         FROM room_members g
        WHERE t.user_id = $2 AND g.user_id = $1 AND g.room_id = t.room_id`, [guestUserId, targetUserId]);
        await tx.query(`DELETE FROM room_members g
        WHERE g.user_id = $1
          AND EXISTS (SELECT 1 FROM room_members t
                       WHERE t.user_id = $2 AND t.room_id = g.room_id)`, [guestUserId, targetUserId]);
        await tx.query(`UPDATE room_members SET user_id = $2 WHERE user_id = $1`, [
            guestUserId,
            targetUserId,
        ]);
        await tx.query(`UPDATE rooms SET created_by = $2 WHERE created_by = $1`, [
            guestUserId,
            targetUserId,
        ]);
    });
}
export async function deleteRoomsData(userId, appId) {
    await withTransaction(async (tx) => {
        await tx.query(`DELETE FROM room_members m
        USING rooms r
        WHERE m.room_id = r.id AND m.user_id = $1 AND r.app_id = $2`, [userId, appId]);
        await tx.query(`DELETE FROM room_members m
        USING rooms r
        WHERE m.room_id = r.id AND r.app_id = $1
          AND NOT EXISTS (SELECT 1 FROM room_members o
                           WHERE o.room_id = r.id AND o.removed_at IS NULL)`, [appId]);
        await tx.query(`DELETE FROM rooms r
        WHERE r.app_id = $1
          AND NOT EXISTS (SELECT 1 FROM room_members o WHERE o.room_id = r.id)`, [appId]);
        await tx.query(`UPDATE rooms SET created_by = NULL WHERE created_by = $1 AND app_id = $2`, [userId, appId]);
    });
}
