import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUser } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

/**
 * GET    /api/ai/generations/[id]  — full row including the raw
 *                                     model response and parsed
 *                                     program (if any). Scoped to
 *                                     the actor.
 * DELETE /api/ai/generations/[id]  — remove a single generation row.
 *                                     The associated Program (if any)
 *                                     stays — only the AI history
 *                                     entry goes.
 */

export async function GET(
  _request: NextRequest,
  { params }: { params: { id: string } },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const row = await prisma.aIGeneration.findFirst({
    where: { id: params.id, userId: user.id },
  });
  if (!row) return NextResponse.json({ error: 'Not found' }, { status: 404 });
  return NextResponse.json(row);
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: { id: string } },
) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const existing = await prisma.aIGeneration.findFirst({
    where: { id: params.id, userId: user.id },
    select: { id: true },
  });
  if (!existing)
    return NextResponse.json({ error: 'Not found' }, { status: 404 });

  await prisma.aIGeneration.delete({ where: { id: params.id } });
  return NextResponse.json({ success: true });
}
