/**
 * In-process cancel adapter for @4runr/sentinel — avoids authenticated HTTP loopback.
 */

import type { CancelAdapter, CancelResult } from '@4runr/sentinel';
import { applyRunKill } from '../runs/run-kill.js';

export function createGatewayCancelAdapter(): CancelAdapter {
  return {
    async cancelRun(runId: string, reason: string): Promise<CancelResult> {
      try {
        const result = await applyRunKill(runId, reason);
        return {
          success: result.applied,
          reason: result.idempotent
            ? 'Run already terminal'
            : result.applied
              ? 'Run killed in store'
              : 'Run kill not applied',
          timestamp: Date.now(),
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        return {
          success: false,
          reason: message,
          timestamp: Date.now(),
        };
      }
    },
  };
}
