export const dynamic = 'force-dynamic';

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth/auth-options';
import { prisma } from '@/lib/db';

/**
 * GET /api/backups/[id]/items - List items in a backup
 */
export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.roles?.includes('admin')) {
      return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
    }

    const { searchParams } = new URL(req.url);
    const entityType = searchParams.get('entityType');
    const limit = parseInt(searchParams.get('limit') || '50');
    const offset = parseInt(searchParams.get('offset') || '0');

    const where: any = { backupId: params.id };
    if (entityType) where.entityType = entityType;

    const [items, total] = await Promise.all([
      prisma.backupItem.findMany({
        where,
        orderBy: { entityType: 'asc' },
        take: limit,
        skip: offset,
        select: {
          id: true,
          entityType: true,
          entityId: true,
          version: true,
          createdAt: true,
          data: true,
        },
      }),
      prisma.backupItem.count({ where }),
    ]);

    return NextResponse.json({ items, total, limit, offset });
  } catch (err: any) {
    console.error('GET /api/backups/[id]/items error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
