// lib/process/stages/human-approval.js — handler for human_approval stages.
//
// On first run, creates an approval_request and returns approval_required so
// the heartbeat worker pauses the task. When the approval is decided, the
// heartbeat-queue's resume path re-enqueues the task. On the second run we
// inspect the approval's status and pass/fail accordingly.

import { createApprovalRequest, getApprovalRequest, consumeApprovalRequest } from '../../approvals.js';
import { applyTemplate } from '../template.js';

export async function executeStage({ case: c, stage, execution }) {
  const config = stage.config || {};
  const intake = c.intake_payload || {};
  const context = c.context || {};

  // If a prior attempt already created the approval, look it up.
  if (execution?.approval_request_id) {
    const approval = getApprovalRequest(execution.approval_request_id);
    if (!approval) {
      return { kind: 'fail', error: 'approval_record_missing' };
    }
    if (approval.status === 'approved') {
      consumeApprovalRequest(approval.id, {
        action_type: 'process.stage.approve',
        matches: (payload) => payload?.case_id === c.id && payload?.stage_slug === stage.slug,
      });
      return {
        kind: 'pass',
        output: {
          approval_id: approval.id,
          decided_by: approval.approved_by || null,
          decided_at: approval.decided_at,
          decision: 'approved',
        },
      };
    }
    if (approval.status === 'denied') {
      return {
        kind: 'fail',
        error: 'approval_denied',
        output: { approval_id: approval.id, decision: 'denied' },
      };
    }
    // Still pending — re-pause.
    return {
      kind: 'pass',
      approval_required: { approval_request_id: approval.id, summary: approval.summary },
      output: { approval_id: approval.id, decision: 'pending' },
    };
  }

  // First run — create the approval.
  const summary = applyTemplate(config.summary_template, { intake, ...context }) ||
    `Approve stage "${stage.name}" for case ${c.title}`;
  const approval = createApprovalRequest({
    action_type: config.action_type || 'process.stage.approve',
    risk: config.risk || 'medium',
    summary,
    payload: {
      case_id: c.id,
      stage_slug: stage.slug,
      definition_slug: c.definition_slug,
    },
    project_id: c.project_id,
  });

  return {
    kind: 'pass',
    approval_required: { approval_request_id: approval.id, summary: approval.summary },
    output: { approval_id: approval.id, decision: 'pending' },
  };
}

export const STAGE_KIND = 'human_approval';
