import { getDB } from '../db.js';
const TRANSITIONS = {
    DRAFT: { next: ['IN_REVIEW'], roles: ['ADMIN', 'EDITOR', 'AUTHOR'] },
    IN_REVIEW: { next: ['APPROVED', 'DRAFT'], roles: ['ADMIN', 'EDITOR'] },
    APPROVED: { next: ['PUBLISHED', 'DRAFT'], roles: ['ADMIN', 'EDITOR'] },
    PUBLISHED: { next: ['ARCHIVED', 'DRAFT'], roles: ['ADMIN'] },
    ARCHIVED: { next: ['DRAFT'], roles: ['ADMIN'] },
};
export function canTransition(from, to, role) {
    const rule = TRANSITIONS[from];
    if (!rule)
        return false;
    return rule.next.includes(to) && rule.roles.includes(role);
}
export function getAvailableTransitions(stage, role) {
    const rule = TRANSITIONS[stage];
    if (!rule || !rule.roles.includes(role))
        return [];
    return rule.next;
}
export async function transitionDocument(documentId, targetStage, userId, role, note) {
    const db = getDB();
    const doc = await db.document.findFirst({ where: { id: documentId, deletedAt: null } });
    if (!doc)
        return { success: false, error: 'Document not found' };
    const currentStage = (doc.workflowStage ?? 'DRAFT');
    if (!canTransition(currentStage, targetStage, role)) {
        return { success: false, error: `Cannot transition from ${currentStage} to ${targetStage}` };
    }
    const updateData = {
        workflowStage: targetStage,
        reviewerId: ['IN_REVIEW', 'APPROVED'].includes(targetStage) ? userId : null,
        reviewNote: note ?? null,
    };
    if (targetStage === 'PUBLISHED') {
        updateData.status = 'PUBLISHED';
        updateData.publishedAt = new Date();
    }
    else if (targetStage === 'DRAFT') {
        updateData.status = 'DRAFT';
    }
    else if (targetStage === 'ARCHIVED') {
        updateData.status = 'ARCHIVED';
    }
    await db.document.update({ where: { id: documentId }, data: updateData });
    await db.version.create({
        data: {
            documentId,
            data: doc.data ?? {},
            changedById: userId,
            changeType: 'UPDATE',
        },
    });
    return { success: true };
}
//# sourceMappingURL=index.js.map