import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET() {
  try {
    const logs = await prisma.activityLog.findMany({
      orderBy: { createdAt: 'desc' }
    });

    const headers = ['id', 'action', 'details', 'status', 'createdAt'];
    const rows = logs.map(log => 
      [log.id, log.action, log.details, log.status, log.createdAt.toISOString()]
        .map(v => `"${String(v).replace(/"/g, '""')}"`)
        .join(',')
    );

    const csvData = [headers.join(','), ...rows].join('\n');

    return new NextResponse(csvData, {
      headers: {
        'Content-Type': 'text/csv',
        'Content-Disposition': 'attachment; filename="system_logs.csv"'
      }
    });
  } catch (error) {
    console.error('Export logs failed:', error);
    return NextResponse.json({ error: 'Failed to export logs' }, { status: 500 });
  }
}
