/**
 * /api/workflows/marketplace
 *
 *   GET                      — list registry + installed recipes/pipelines (merged)
 *   POST { action: 'sync' }                     — pull registry.json from forge-workflow
 *   POST { action: 'install',   kind, name }    — download yaml → save to local dir
 *   POST { action: 'uninstall', kind, name }    — remove the local yaml file
 *
 * `kind` is "recipe" | "pipeline". Built-in pipelines are protected
 * elsewhere (lib/workflow-marketplace.ts excludes them from `installed`,
 * and the pipelines delete-workflow route rejects them).
 */

import { NextResponse } from 'next/server';
import {
  syncMarketplace,
  listMarketplace,
  installFromMarketplace,
  uninstallFromMarketplace,
  type WorkflowKind,
} from '@/lib/workflow-marketplace';

export async function GET() {
  return NextResponse.json(listMarketplace());
}

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 === 'sync') {
    const r = await syncMarketplace();
    return NextResponse.json(r, { status: r.ok ? 200 : 502 });
  }

  if (action === 'install' || action === 'uninstall') {
    const kind = body.kind as WorkflowKind;
    const name = body.name;
    if (kind !== 'recipe' && kind !== 'pipeline') {
      return NextResponse.json({ ok: false, error: 'kind must be "recipe" or "pipeline"' }, { status: 400 });
    }
    if (!name) return NextResponse.json({ ok: false, error: 'name required' }, { status: 400 });
    const r = action === 'install'
      ? await installFromMarketplace(kind, name, { target_name: body.target_name, overwrite: !!body.overwrite })
      : uninstallFromMarketplace(kind, name);
    return NextResponse.json(r, { status: r.ok ? 200 : 400 });
  }

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