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] - Get backup detail with item summary
 */
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 backup = await prisma.backup.findUnique({
      where: { id: params.id },
    });

    if (!backup) {
      return NextResponse.json({ error: 'Backup not found' }, { status: 404 });
    }

    // Get item counts by entity type
    const itemCounts = await prisma.backupItem.groupBy({
      by: ['entityType'],
      where: { backupId: params.id },
      _count: { id: true },
    });

    return NextResponse.json({
      backup,
      itemSummary: itemCounts.map((ic: any) => ({
        entityType: ic.entityType,
        count: ic._count.id,
      })),
    });
  } catch (err: any) {
    console.error('GET /api/backups/[id] error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}

/**
 * DELETE /api/backups/[id] - Delete a backup
 */
export async function DELETE(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 backup = await prisma.backup.findUnique({ where: { id: params.id } });
    if (!backup) {
      return NextResponse.json({ error: 'Backup not found' }, { status: 404 });
    }

    await prisma.backup.delete({ where: { id: params.id } });

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error('DELETE /api/backups/[id] error:', err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
