/**
 * GET  /api/jobs    list all jobs
 * POST /api/jobs    create a job
 */

import { NextResponse } from 'next/server';
import { listJobs, createJob } from '@/lib/jobs/store';

export async function GET() {
  return NextResponse.json({ jobs: listJobs() });
}

export async function POST(req: Request) {
  let body: any = {};
  try { body = await req.json(); } catch {}
  if (!body?.name || !body?.source_connector || !body?.source_tool || !body?.dedup_field || !body?.dispatch_type || !body?.dispatch_params) {
    return NextResponse.json({ error: 'name, source_connector, source_tool, dedup_field, dispatch_type, dispatch_params are required' }, { status: 400 });
  }
  if (body.dispatch_type !== 'pipeline' && body.dispatch_type !== 'chat') {
    return NextResponse.json({ error: "dispatch_type must be 'pipeline' or 'chat'" }, { status: 400 });
  }
  const job = createJob({
    name: String(body.name),
    enabled: body.enabled !== false,
    schedule_interval_minutes: Number(body.schedule_interval_minutes) || 30,
    source_connector: String(body.source_connector),
    source_tool: String(body.source_tool),
    source_input: body.source_input || {},
    items_path: body.items_path || '',
    dedup_field: String(body.dedup_field),
    dispatch_type: body.dispatch_type,
    dispatch_params: body.dispatch_params,
    skills: Array.isArray(body.skills) ? body.skills.map((s: unknown) => String(s)) : [],
    schedule_kind: ['once', 'cron', 'manual'].includes(body.schedule_kind) ? body.schedule_kind : 'period',
    schedule_at: body.schedule_at ? String(body.schedule_at) : null,
    schedule_cron: body.schedule_cron ? String(body.schedule_cron) : null,
    mark_existing_as_seen: body.mark_existing_as_seen !== false,
  });
  return NextResponse.json({ job });
}
