import { ParsedEDILine } from '@/types';

export function parseStarkeyEDI(csvText: string): ParsedEDILine[] {
  const lines: ParsedEDILine[] = [];

  const rawLines = csvText.split('\n');
  let currentCentreCode = '';

  for (const rawLine of rawLines) {
    const trimmed = rawLine.trim();
    if (!trimmed) continue;

    const cols = trimmed.split(';');
    if (cols.length < 14) continue;

    // col[6] = famille
    const famille = (cols[6] ?? '').trim();
    // Famille filtering moved to filterEDILines for category support

    // col[2] = type facture, skip credit notes (AV = avoir)
    const typeFacture = (cols[2] ?? '').trim();
    if (typeFacture === 'AV') continue;

    // col[0] = centre code (can be empty, carry forward from previous)
    const centreCode = (cols[0] ?? '').trim();
    if (centreCode) currentCentreCode = centreCode;

    // col[10] = taux remise ×100 (6800 = 68%)
    const discountRaw = parseFloat((cols[10] ?? '0').trim()) || 0;
    const discountPct = discountRaw / 100;

    // col[13] = montant HT net (prix facturé unitaire)
    const netPrice = parseFloat((cols[13] ?? '0').trim().replace(',', '.')) || 0;
    if (netPrice <= 0) continue;

    const quantity = parseInt((cols[9] ?? '1').trim()) || 1;

    // Unit price = netPrice / quantity (col[13] is total HT for the line)
    const unitPrice = quantity > 0 ? Math.round((netPrice / quantity) * 100) / 100 : netPrice;

    lines.push({
      centre_code: currentCentreCode,
      centre_name: '', // Starkey uses codes, resolved later via centre_codes table
      code_article: (cols[7] ?? '').trim(),
      description: (cols[8] ?? '').trim(),
      quantity,
      unit_price: unitPrice,
      discount_pct: discountPct,
      invoice_number: (cols[3] ?? '').trim(),
      invoice_date: (cols[4] ?? '').trim(),
      sign: typeFacture === 'AV' ? '-' : '+',
      famille,
    });
  }

  return lines;
}
