import { query, UUID2hex, HEX2uuid } from '@commtool/sql-query';
/**
* Create an action instance from a template and trigger, without Express req/res.
*
* Mirrors the core logic of createAction in controller.js but takes plain
* parameters instead of Express objects. No template rendering, no events.
*
* @param {string} templateUID - UUID string of the actionT ObjectBase entry (not the bot UID)
* @param {string} triggerUID - UUID string of the trigger object (the group)
* @param {object} data - Data to store in the action's Data column
* @returns {Promise<{success: boolean, UID?: string, error?: string}>}
*/
export const createActionFromTemplate = async (templateUID, triggerUID, data) => {
const UIDtemplate = UUID2hex(templateUID);
const UIDtrigger = UUID2hex(triggerUID);
// Validate trigger exists
const triggers = await query(
`SELECT Type, Display FROM ObjectBase WHERE UID = ?`,
[UIDtrigger],
);
if (triggers.length === 0) {
return { success: false, error: `Trigger ${triggerUID} not found` };
}
// Validate template exists
const templates = await query(
`SELECT Data FROM ObjectBase WHERE UID = ? AND Type = 'actionT'`,
[UIDtemplate],
);
if (templates.length === 0) {
return { success: false, error: `Template ${templateUID} not found or not an actionT` };
}
const triggerType = triggers[0].Type;
const triggerDisplay = triggers[0].Display || '';
// Generate a new UUID
const [{ UID: newUID }] = await query(`SELECT UIDV1() AS UID`, []);
const UIDstring = HEX2uuid(newUID);
const actionData = {
...data,
UID: UIDstring,
TriggerType: triggerType,
UIDTrigger: triggerUID,
};
const title = `Beiträge: ${triggerDisplay}`;
await query(
`INSERT INTO ObjectBase (UID, UIDBelongsTo, Type, Title, Display, SortName, FullTextIndex, dindex, Data)
VALUES (?, ?, 'action', ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE Data = VALUES(Data)`,
[
newUID,
UIDtrigger,
title,
title,
triggerDisplay,
'',
10000,
JSON.stringify(actionData),
],
);
await query(
`INSERT IGNORE INTO Links (UID, Type, UIDTarget) VALUES (?, 'action', ?)`,
[UIDtemplate, newUID],
);
return { success: true, UID: UIDstring };
};