/**
 * @internal
 * consistency/parse-plan-approval.mjs — normalize plan_approval.json (C21).
 *
 * Input: parsed JSON object (or null/undefined).
 * Output:
 *   {
 *     decision:  'approved' | 'rejected' | 'revise' | 'unknown',
 *     actor:     string,
 *     timestamp: string,
 *     plan_hash: string | null,
 *     spec_hash: string | null,
 *     note:      string | null,
 *     iteration: number
 *   }
 *
 * Tolerant of missing / malformed input — returns null-shaped fields so rules
 * can decide how to react.
 */

const VALID_DECISIONS = new Set(['approved', 'rejected', 'revise'])

/**
 * @param {object | null | undefined} record
 */
export function parsePlanApproval(record) {
	if (!record || typeof record !== 'object') {
		return {
			decision: 'unknown',
			actor: '',
			timestamp: '',
			plan_hash: null,
			spec_hash: null,
			note: null,
			iteration: 0,
		}
	}
	const decision = VALID_DECISIONS.has(record.decision) ? record.decision : 'unknown'
	const actor = typeof record.actor === 'string' ? record.actor : ''
	const timestamp = typeof record.timestamp === 'string' ? record.timestamp : ''
	const plan_hash = typeof record.plan_hash === 'string' ? record.plan_hash : null
	const spec_hash = typeof record.spec_hash === 'string' ? record.spec_hash : null
	const note = typeof record.note === 'string' ? record.note : null
	const iteration =
		typeof record.iteration === 'number' &&
		Number.isFinite(record.iteration) &&
		record.iteration > 0
			? record.iteration
			: 0
	return { decision, actor, timestamp, plan_hash, spec_hash, note, iteration }
}
