import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import * as XLSX from 'xlsx';

export async function POST(request: Request) {
  try {
    const body = await request.json();
    // Accept both `leadIds` and `ids` keys (different pages use different names)
    const ids   = body.leadIds ?? body.ids ?? null;
    const format = body.format ?? 'csv';

    const leads = await prisma.lead.findMany({
      where: ids && ids.length > 0 ? { id: { in: ids } } : {},
    });

    if (leads.length === 0) {
      return NextResponse.json({ error: 'No leads found to export' }, { status: 404 });
    }

    const data = leads.map(l => ({
      'Company Name': l.businessName,
      'Website': l.website,
      'Email': l.email,
      'Phone': l.phone,
      'Address': l.address,
      'City': l.city,
      'State': l.state,
      'Country': l.country,
      'Category': l.category,
      'Source': l.source,
      'Confidence': l.confidenceScore,
      'Status': l.status,
      'Created': l.createdAt.toISOString(),
    }));

    // Log the export
    await prisma.activityLog.create({
      data: {
        action: 'export',
        details: `Exported ${leads.length} leads in ${format} format.`
      }
    });

    if (format === 'xlsx') {
      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.json_to_sheet(data);
      XLSX.utils.book_append_sheet(wb, ws, 'Leads');
      const buffer = XLSX.write(wb, { type: 'buffer', bookType: 'xlsx' });
      
      return new Response(buffer, {
        headers: {
          'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'Content-Disposition': `attachment; filename="LeadForge_Export_${new Date().toISOString()}.xlsx"`,
        },
      });
    } else {
      // Default to CSV
      const headers = Object.keys(data[0]).join(',');
      const rows = data.map(obj => Object.values(obj).map(v => `"${v}"`).join(',')).join('\n');
      const csv = `${headers}\n${rows}`;

      return new Response(csv, {
        headers: {
          'Content-Type': 'text/csv',
          'Content-Disposition': `attachment; filename="LeadForge_Export_${new Date().toISOString()}.csv"`,
        },
      });
    }

  } catch (error) {
    console.error('Export error:', error);
    return NextResponse.json({ error: 'Failed to export leads' }, { status: 500 });
  }
}
