// @ts-check
/**
* @import {treeAction} from './../../types.js'
*/
import { query, HEX2uuid } from '@commtool/sql-query'
import rebuildFees from '../rebuildFees.js'
import { errorLoggerUpdate } from '../../utils/requestLogger.js'
/**
* Handles `family` and `familyB` migration actions.
*
* Moves a person's family or familyFees link from the old family object to the
* new one. If the old family object has no remaining members the orphaned Member
* row is deleted; otherwise family fees are recalculated for it.
* Either way, fees are recalculated for the new family object.
*
* @param {treeAction} action
* @returns {Promise<void>}
*/
export const migrateFamilyAction = async (action) => {
try {
await query(
`DELETE FROM Links WHERE UID=? AND Type IN ('family','familyFees') AND UIDTarget=?`,
[action.UIDObjectID, action.UIDoldTarget],
)
const rest = await query(
`SELECT Links.UID FROM Links
WHERE Links.UIDTarget=? AND Type IN ('family','familyFees')`,
[action.UIDoldTarget],
)
if (rest.length > 0) {
rebuildFees(action.UIDoldTarget, HEX2uuid(action.UIDroot))
} else {
query(`DELETE FROM Member WHERE UID=?`, [action.UIDoldTarget])
}
await query(
`INSERT IGNORE INTO Links (UID, Type, UIDTarget) VALUES (?, ?, ?)`,
[
action.UIDObjectID,
action.Type === 'familyB' ? 'familyFees' : 'family',
action.UIDnewTarget,
],
)
rebuildFees(action.UIDnewTarget, HEX2uuid(action.UIDroot))
}
catch (e) {
errorLoggerUpdate(e || new Error('treeMigrate.familyAction: Unknown error occurred'))
}
}