import { notionRequest, type JsonRecord } from './request.ts'
import { inputRecord, optionalRecord, optionalString, requiredString } from './validation.ts'
type AppendBlockChildrenResponse = {
results?: unknown[]
[key: string]: unknown
}
/** Preview or append child blocks to a Notion page or block. */
export default async function appendBlockChildren(params: Record<string, unknown>) {
const input = inputRecord(params)
const blockId = requiredString(input, 'blockId')
const children = input.children
if (!Array.isArray(children) || children.length === 0) {
throw new Error('children must be a non-empty array of Notion block objects.')
}
// position: { type: 'after_block', after_block: { id } } | { type: 'start' } | { type: 'end' }
const payload: JsonRecord = {
children,
position: optionalRecord(input, 'position'),
}
const path = '/blocks/' + encodeURIComponent(blockId) + '/children'
const account = optionalString(input, 'account')
const integration = optionalString(input, 'integration')
if (input.dryRun === true) {
return { dryRun: true, method: 'PATCH', path, payload }
}
if (input.confirm !== true) {
throw new Error('Appending Notion blocks requires confirm: true after explicit user approval of the destination and content. Use dryRun: true to preview.')
}
const result = await notionRequest<AppendBlockChildrenResponse>(path, {
method: 'PATCH',
body: payload,
account,
integration,
})
return {
ok: true,
appendedCount: Array.isArray(result.results) ? result.results.length : 0,
}
}