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

/**
 * DELETE /api/admin/ai/generations  — admin-only "clear all generation
 *                                       history". Body optionally narrows:
 *                                       { userId?: string }  — only that user
 *                                       { olderThanDays?: number } — purge older
 *                                       Default = wipe ALL rows.
 */

const bodySchema = z.object({
  userId: z.string().optional(),
  olderThanDays: z.number().int().positive().optional(),
});

export async function DELETE(request: NextRequest) {
  const me = await getCurrentUser();
  if (!me) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  if (!me.isAdmin)
    return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

  let body: unknown = {};
  try {
    body = await request.json();
  } catch {
    /* empty body OK */
  }
  const parsed = bodySchema.safeParse(body);
  const filter = parsed.success ? parsed.data : {};

  const where: Record<string, unknown> = {};
  if (filter.userId) where.userId = filter.userId;
  if (filter.olderThanDays) {
    where.createdAt = {
      lt: new Date(Date.now() - filter.olderThanDays * 86_400_000),
    };
  }

  const result = await prisma.aIGeneration.deleteMany({ where });
  return NextResponse.json({ deleted: result.count });
}
