import { NextRequest, NextResponse } from 'next/server';
import { getAllContacts } from '@/lib/db';

function escapeCSV(value: string | null | undefined): string {
  if (value === null || value === undefined) return '';
  const str = String(value);
  // Escape quotes and wrap in quotes if needed
  if (str.includes(',') || str.includes('"') || str.includes('\n') || str.includes('\r')) {
    return `"${str.replace(/"/g, '""')}"`;
  }
  return str;
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    const search = searchParams.get('search') || undefined;
    const status = searchParams.get('status') || undefined;
    const bot = searchParams.get('bot') || undefined;

    // Fetch all matching contacts (higher limit for export)
    const contacts = getAllContacts({
      search,
      status,
      bot,
      limit: 10000,
      offset: 0,
    }) as Array<{
      id: string;
      phone: string;
      name: string | null;
      email: string | null;
      status: string;
      tags: string;
      fields_json: string;
      message_count: number;
      last_contact: string;
      first_contact: string;
      bot_name: string | null;
      assigned_bot_id: string | null;
    }>;

    // CSV header
    const headers = [
      'ID',
      'Name',
      'Phone',
      'Email',
      'Status',
      'Assigned Bot',
      'Message Count',
      'First Contact',
      'Last Contact',
      'Tags',
    ];

    const rows = contacts.map((c) => {
      let tags = '';
      try {
        const parsed = JSON.parse(c.tags);
        tags = Array.isArray(parsed) ? parsed.join('; ') : '';
      } catch {
        tags = '';
      }

      return [
        escapeCSV(c.id),
        escapeCSV(c.name),
        escapeCSV(c.phone),
        escapeCSV(c.email),
        escapeCSV(c.status),
        escapeCSV(c.bot_name),
        String(c.message_count || 0),
        escapeCSV(c.first_contact),
        escapeCSV(c.last_contact),
        escapeCSV(tags),
      ].join(',');
    });

    const csv = [headers.join(','), ...rows].join('\r\n');
    const dateStr = new Date().toISOString().split('T')[0];

    return new NextResponse(csv, {
      status: 200,
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': `attachment; filename="contacts-export-${dateStr}.csv"`,
        'Cache-Control': 'no-cache',
      },
    });
  } catch (error) {
    console.error('GET /api/contacts/export error:', error);
    return NextResponse.json(
      { error: 'Failed to export contacts' },
      { status: 500 }
    );
  }
}
