/**
 * POST /api/schedules/:id/stop
 *
 * One-shot Pause + Cancel: disables the schedule AND cancels every
 * inflight pipeline it launched. Use when user wants to fully halt.
 */

import { NextResponse } from 'next/server';
import {
  getSchedule,
  updateSchedule,
  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 });

  updateSchedule(id, { enabled: false });

  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/stop] cancelPipeline(${run.target_id}) failed: ${(e as Error).message}`);
    }
  }

  return NextResponse.json({ ok: true, cancelled });
}
