import { isGitTaskStateCanonicalAuthority } from "./task-state-canonical-authority.js";
import { commitCanonicalTaskStateEvents } from "./task-state-canonical-commit.js";
import { draftCreatedEvent, draftUpdatedEvent } from "./task-state-event-draft.js";
export async function finalizeCanonicalCreateTask(input) {
    if (!isGitTaskStateCanonicalAuthority(input.ctx)) {
        return null;
    }
    const event = draftCreatedEvent(input.task, {
        commandName: input.commandName,
        moduleId: "task-engine",
        actorId: input.actor,
        clientMutationId: input.clientMutationId,
        phaseKey: input.task.phaseKey
    });
    return commitCanonicalTaskStateEvents({
        ctx: input.ctx,
        store: input.store,
        planning: input.planning,
        events: [event],
        policyApproval: input.policyApproval
    });
}
export async function finalizeCanonicalUpdateTask(input) {
    if (!isGitTaskStateCanonicalAuthority(input.ctx)) {
        return null;
    }
    const values = {
        title: input.task.title,
        type: input.task.type,
        status: input.task.status,
        priority: input.task.priority,
        phase: input.task.phase,
        phaseKey: input.task.phaseKey,
        summary: input.task.summary,
        metadata: input.task.metadata
    };
    if (input.changedFields.includes("phase") && input.task.phase === undefined) {
        values.phase = null;
    }
    if (input.changedFields.includes("phaseKey") && input.task.phaseKey === undefined) {
        values.phaseKey = null;
    }
    const event = draftUpdatedEvent(input.task.id, input.changedFields, input.store, {
        commandName: input.commandName,
        moduleId: "task-engine",
        actorId: input.actor,
        clientMutationId: input.clientMutationId,
        phaseKey: input.task.phaseKey
    }, values, input.ctx.workspacePath);
    return commitCanonicalTaskStateEvents({
        ctx: input.ctx,
        store: input.store,
        planning: input.planning,
        events: [event],
        policyApproval: input.policyApproval
    });
}
