/**
 * /api/jobs/recipes
 *
 *   GET                              — list installed recipes
 *   GET ?name=<name>                 — fetch a single recipe (UI form metadata)
 *   POST   { action: 'instantiate',  name, params }   — create Job from recipe
 *   POST   { action: 'upload',       yaml }            — save a user-supplied recipe yaml
 *   POST   { action: 'delete',       name }            — delete a recipe file
 */

import { NextResponse } from 'next/server';
import {
  listRecipes,
  getRecipe,
  saveRecipeYaml,
  deleteRecipe,
  instantiateRecipe,
} from '@/lib/jobs/recipes';

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const name = searchParams.get('name');
  if (name) {
    const r = getRecipe(name);
    if (!r) return NextResponse.json({ error: 'not found' }, { status: 404 });
    return NextResponse.json({ recipe: r });
  }
  return NextResponse.json({ recipes: listRecipes() });
}

export async function POST(req: Request) {
  let body: any;
  try { body = await req.json(); }
  catch { return NextResponse.json({ ok: false, error: 'invalid JSON body' }, { status: 400 }); }
  const action = body?.action;

  if (action === 'instantiate') {
    if (!body.name) return NextResponse.json({ ok: false, error: 'name required' }, { status: 400 });
    const r = instantiateRecipe(body.name, body.params || {});
    if (!r.ok) return NextResponse.json(r, { status: 400 });
    return NextResponse.json(r);
  }

  if (action === 'upload') {
    if (typeof body.yaml !== 'string' || !body.yaml.trim()) {
      return NextResponse.json({ ok: false, error: 'yaml required' }, { status: 400 });
    }
    const r = saveRecipeYaml(body.yaml);
    return NextResponse.json(r, { status: r.ok ? 200 : 400 });
  }

  if (action === 'delete') {
    if (!body.name) return NextResponse.json({ ok: false, error: 'name required' }, { status: 400 });
    const ok = deleteRecipe(body.name);
    return NextResponse.json({ ok }, { status: ok ? 200 : 404 });
  }

  return NextResponse.json({ ok: false, error: 'unknown action' }, { status: 400 });
}
