/**
 * POST /api/schedules/:id/cancel
 *
 * Cancel all inflight pipelines this schedule launched.
 * Does NOT change enabled (use /stop for that).
 */

import { NextResponse } from 'next/server';
import { getSchedule, listInflightForSchedule } from '@/lib/schedules/store';
import { cancelPipeline } from '@/lib/pipeline';

export async function POST(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const s = getSchedule(id);
  if (!s) return NextResponse.json({ error: 'schedule not found' }, { status: 404 });

  let cancelled = 0;
  for (const run of listInflightForSchedule(id)) {
    // Phase 1: target_id is always a pipeline_id.
    try { if (cancelPipeline(run.target_id)) cancelled++; }
    catch (e) {
      console.warn(`[schedules/cancel] cancelPipeline(${run.target_id}) failed: ${(e as Error).message}`);
    }
  }

  return NextResponse.json({ cancelled });
}
