/**
 * POST /api/tasks/bulk-delete
 *
 *   { older_than_days?: number, before?: ISO, statuses?: string[] }
 *
 * Deletes tasks matching the filter. Running tasks are skipped — only
 * terminal-state rows (done/failed/cancelled by default) are removed.
 *
 *   older_than_days: 7  → cutoff = now - 7 days
 *   before: "ISO"       → explicit cutoff
 *   statuses: ["failed"] → narrow to just failures (default = done+failed+cancelled)
 *
 * Returns { removed: <count>, before: <ISO cutoff> }.
 */

import { NextResponse } from 'next/server';
import { bulkDeleteTasks } from '@/lib/task-manager';
import type { TaskStatus } from '@/src/types';

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 });
  }

  const validStatuses: TaskStatus[] = ['queued', 'running', 'done', 'failed', 'cancelled'];
  let statuses: TaskStatus[] | undefined;
  if (Array.isArray(body.statuses) && body.statuses.length) {
    statuses = (body.statuses as string[])
      .filter((s) => validStatuses.includes(s as TaskStatus))
      .filter((s) => s !== 'running' && s !== 'queued') as TaskStatus[];
    if (statuses.length === 0) {
      return NextResponse.json({ error: 'statuses filter excluded everything (running/queued can never be bulk-deleted)' }, { status: 400 });
    }
  }

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