// @ts-check
/**
* @import {treeAction} from './../../types.js'
*/
import { query, HEX2uuid } from '@commtool/sql-query'
import { addUpdateList } from '../../server.ws.js'
import { publishEvent } from '../../utils/events.js'
import { errorLoggerUpdate } from '../../utils/requestLogger.js'
/**
* Handles the `list` remove action.
*
* Fired when a list entry is deleted. Cleans up any `member`, `member0`, and
* `dynamic` Links that dlists created for this entry, and notifies subscribers
* via event-bus and WebSocket.
*
* The entry itself has already been deleted by the time this action runs;
* only the downstream dlist bookkeeping remains.
*
* @param {treeAction} action
* @returns {Promise<void>}
*/
export const removeListEntryAction = async (action) => {
try {
const timestamp = action.timestamp
? (typeof action.timestamp === 'string' ? parseFloat(action.timestamp) : action.timestamp)
: null
const asOf = timestamp ? `FOR SYSTEM_TIME AS OF FROM_UNIXTIME(${timestamp})` : ''
const mLinks = await query(
`SELECT Links.UIDTarget, Links.Type
FROM Links ${asOf}
WHERE Links.UID=? AND Links.Type IN ('member','member0')`,
[action.UIDObjectID],
)
if (mLinks.length > 0) {
await query(
`DELETE FROM Links WHERE UID=? AND Type IN ('member','member0','dynamic')`,
[action.UIDObjectID],
)
const UID = HEX2uuid(action.UIDObjectID)
const UIDBelongsTo = HEX2uuid(action.UIDBelongsTo)
for (const ml of mLinks) {
if (ml.Type === 'member') {
publishEvent(`/remove/dlist/entry/${HEX2uuid(ml.UIDTarget)}`, {
organization: HEX2uuid(action.UIDroot),
data: [UID],
})
publishEvent(`/remove/dlist/person/${HEX2uuid(ml.UIDTarget)}`, {
organization: HEX2uuid(action.UIDroot),
data: [UIDBelongsTo],
})
addUpdateList(ml.UIDTarget)
}
}
}
} catch (e) {
errorLoggerUpdate(e || new Error('removeListEntryAction: Unknown error occurred'))
}
}