/**
 * POST /api/jobs/<id>/cancel
 *
 * Stop the sequential drain for this Job. Clears `next_run_at` so the
 * scheduler won't pick the Job up again automatically. Pipelines that
 * are already running are NOT touched — the user can cancel those
 * individually on the Pipeline view if they want.
 *
 * Query / body:
 *   cancel_inflight=1  (optional) — also cancel any pipeline this Job
 *                       dispatched that's still running. Best-effort.
 */

import { NextResponse } from 'next/server';
import { getJob, cancelJobDrain, listJobDispatchedPipelines } from '@/lib/jobs/store';
import { cancelPipeline } from '@/lib/pipeline';

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

  const url = new URL(req.url);
  const cancelInflight = url.searchParams.get('cancel_inflight') === '1';

  const stopped = cancelJobDrain(id);

  let cancelledPipelines = 0;
  if (cancelInflight) {
    // Best-effort: walk the most-recent dispatched pipelines and
    // cancel ones still running. cancelPipeline is a no-op for
    // already-terminal pipelines, so this stays idempotent.
    for (const p of listJobDispatchedPipelines(id, 50)) {
      if (p.pipeline_status === 'running' || p.pipeline_status === 'pending') {
        try {
          if (cancelPipeline(p.pipeline_id)) cancelledPipelines++;
        } catch (e) {
          console.warn(`[jobs/cancel] cancelPipeline(${p.pipeline_id}) failed: ${(e as Error).message}`);
        }
      }
    }
  }

  return NextResponse.json({
    ok: true,
    drain_stopped: stopped,
    cancelled_pipelines: cancelledPipelines,
    cancel_inflight_requested: cancelInflight,
  });
}
