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

/**
 * GET /api/ai/generations  — list this user's AI generations,
 *                             newest first. Supports ?limit=&offset=
 *                             (default 25 / 0).
 */
export async function GET(request: NextRequest) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

  const sp = request.nextUrl.searchParams;
  const limit = Math.min(parseInt(sp.get('limit') || '25'), 100);
  const offset = Math.max(parseInt(sp.get('offset') || '0'), 0);

  const rows = await prisma.aIGeneration.findMany({
    where: { userId: user.id },
    orderBy: { createdAt: 'desc' },
    take: limit + 1,
    skip: offset,
    select: {
      id: true,
      templateName: true,
      userInput: true,
      provider: true,
      model: true,
      tokensIn: true,
      tokensOut: true,
      durationMs: true,
      status: true,
      errorMessage: true,
      appliedProgramId: true,
      createdAt: true,
    },
  });
  const hasMore = rows.length > limit;
  return NextResponse.json({
    data: rows.slice(0, limit),
    hasMore,
  });
}
