import { NextResponse } from 'next/server';
import { listPrompts, createPrompt } from '@/lib/prompts/store';

// GET /api/prompts — list all stored prompts
export async function GET() {
  return NextResponse.json(listPrompts());
}

// POST /api/prompts — create a new prompt
//   body: { name, prompt, executor?: { agent?, skills?, config? } }
export async function POST(req: Request) {
  let body: any;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: 'invalid json body' }, { status: 400 });
  }
  if (!body?.name || typeof body.name !== 'string') {
    return NextResponse.json({ error: 'name required' }, { status: 400 });
  }
  if (!body?.prompt || typeof body.prompt !== 'string') {
    return NextResponse.json({ error: 'prompt required' }, { status: 400 });
  }
  try {
    const p = createPrompt({
      name: body.name,
      prompt: body.prompt,
      executor: body.executor,
    });
    return NextResponse.json(p, { status: 201 });
  } catch (e: any) {
    const conflict = String(e?.message || '').includes('already exists');
    return NextResponse.json({ error: e.message }, { status: conflict ? 409 : 400 });
  }
}
