import { Router, Request, Response } from 'express';
import { getJob, getJobLeads } from '../engine/queue';
import { Lead, Owner } from '../types';

const router = Router();

/**
 * GET /api/exports/:id?format=csv|json — Export job results
 */
router.get('/:id', (req: Request, res: Response) => {
  const job = getJob(req.params.id as string);
  if (!job) {
    return res.status(404).json({ error: 'Job not found' });
  }

  if (job.status !== 'complete') {
    return res.status(400).json({
      error: 'Job is not complete',
      status: job.status,
    });
  }

  const leads = getJobLeads(job.id);
  const rawFormat = req.query.format;
  const format = (Array.isArray(rawFormat) ? rawFormat[0] : rawFormat) as string || 'json';

  if (format === 'csv') {
    const csv = leadsToCSV(leads);
    res.setHeader('Content-Type', 'text/csv');
    res.setHeader('Content-Disposition', `attachment; filename="reonomy-export-${job.id}.csv"`);
    return res.send(csv);
  }

  // Default: JSON
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Disposition', `attachment; filename="reonomy-export-${job.id}.json"`);
  return res.json({
    exportDate: new Date().toISOString(),
    jobId: job.id,
    searchId: job.searchId,
    totalLeads: leads.length,
    leads,
  });
});

/**
 * Convert leads to CSV format
 */
function leadsToCSV(leads: Lead[]): string {
  const headers = [
    'Property Address',
    'Property ID',
    'Scrape Date',
    'Property Type',
    'Units',
    'Building Area',
    'Year Built',
    'Lot Size',
    'Zoning',
    'Owner Name',
    'Phone 1',
    'Phone 1 Type',
    'Phone 2',
    'Phone 2 Type',
    'Phone 3',
    'Phone 3 Type',
    'Email 1',
    'Email 2',
    'Last Sale Date',
    'Last Sale Price',
    'Buyer',
    'Seller',
    'Deed Type',
    'Lender',
    'Loan Amount',
    'Assessed Value',
    'Tax Amount',
  ];

  const rows: string[][] = [];

  for (const lead of leads) {
    // One row per owner (or one row if no owners)
    const owners = lead.owners && lead.owners.length > 0 ? lead.owners : [null];

    for (const owner of owners) {
      const row: string[] = [
        lead.propertyAddress,
        lead.propertyId,
        lead.scrapeDate,
        lead.building?.propertyType || '',
        lead.building?.units || '',
        lead.building?.buildingArea || '',
        lead.building?.yearBuilt || '',
        lead.building?.lotSize || '',
        lead.building?.zoning || '',
        owner?.name || '',
        owner?.phones[0]?.number || '',
        owner?.phones[0]?.type || '',
        owner?.phones[1]?.number || '',
        owner?.phones[1]?.type || '',
        owner?.phones[2]?.number || '',
        owner?.phones[2]?.type || '',
        owner?.emails[0] || '',
        owner?.emails[1] || '',
        lead.sales?.[0]?.saleDate || '',
        lead.sales?.[0]?.price || '',
        lead.sales?.[0]?.buyer || '',
        lead.sales?.[0]?.seller || '',
        lead.sales?.[0]?.deedType || '',
        lead.debt?.[0]?.lender || '',
        lead.debt?.[0]?.amount || '',
        lead.tax?.assessedValue || '',
        lead.tax?.taxAmount || '',
      ];
      rows.push(row);
    }
  }

  const csvLines = [
    headers.map(escapeCSV).join(','),
    ...rows.map((row) => row.map(escapeCSV).join(',')),
  ];

  return csvLines.join('\n');
}

function escapeCSV(value: string): string {
  if (value.includes(',') || value.includes('"') || value.includes('\n')) {
    return `"${value.replace(/"/g, '""')}"`;
  }
  return value;
}

export default router;
