/**
 * POST /api/pipelines/bulk-delete
 *
 *   { older_than_days?: number, before?: ISO, statuses?: string[] }
 *
 * Same shape as /api/tasks/bulk-delete. Skips running/pending pipelines
 * — only terminal ones (done/failed/cancelled) are removed.
 */

import { NextResponse } from 'next/server';
import { bulkDeletePipelines } from '@/lib/pipeline';

export async function POST(req: Request) {
  let body: any = {};
  try { body = await req.json(); } catch {}

  let before: string;
  if (typeof body.before === 'string' && body.before) {
    before = body.before;
  } else if (Number.isFinite(Number(body.older_than_days))) {
    const days = Math.max(0, Number(body.older_than_days));
    before = new Date(Date.now() - days * 86_400_000).toISOString();
  } else {
    return NextResponse.json({ error: 'pass `older_than_days` (number) or `before` (ISO timestamp)' }, { status: 400 });
  }

  type PipelineStatus = 'done' | 'failed' | 'cancelled';
  let statuses: PipelineStatus[] | undefined;
  if (Array.isArray(body.statuses) && body.statuses.length) {
    const valid: PipelineStatus[] = ['done', 'failed', 'cancelled'];
    statuses = (body.statuses as string[]).filter((s) => valid.includes(s as PipelineStatus)) as PipelineStatus[];
    if (statuses.length === 0) {
      return NextResponse.json({ error: 'statuses must include done/failed/cancelled (running/pending cannot be bulk-deleted)' }, { status: 400 });
    }
  }

  const removed = bulkDeletePipelines({ before, statuses });
  return NextResponse.json({ removed, before, statuses: statuses ?? ['done', 'failed', 'cancelled'] });
}
