/**
 * POST /api/schedules/:id/run[?cancel_inflight=1]
 *
 * Manual fire (trigger='manual'). 409 if busy unless cancel_inflight=1.
 */

import { NextResponse } from 'next/server';
import { getSchedule, listInflightForSchedule } from '@/lib/schedules/store';
import { executeSchedule, isScheduleBusy } from '@/lib/schedules/scheduler';
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 });

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

  const busy = isScheduleBusy(id);
  if (busy.busy) {
    if (!cancelInflight) {
      return NextResponse.json({
        error: `schedule is busy: ${busy.reason}. Pass ?cancel_inflight=1 to cancel + run anyway.`,
        busy: true,
        reason: busy.reason,
      }, { status: 409 });
    }
    // Cancel each inflight pipeline before firing a new one.
    // Phase 1: target_id is always a pipeline_id.
    for (const run of listInflightForSchedule(id)) {
      try { cancelPipeline(run.target_id); }
      catch (e) {
        console.warn(`[schedules/run] cancelPipeline(${run.target_id}) failed: ${(e as Error).message}`);
      }
    }
  }

  try {
    const targetId = await executeSchedule(s, 'manual');
    return NextResponse.json({ target_id: targetId, pipeline_id: targetId }, { status: 202 });
  } catch (e) {
    return NextResponse.json({ error: (e as Error).message }, { status: 500 });
  }
}
