import * as XLSX from 'xlsx';
import { ParsedEDILine } from '@/types';

export function parseResoundEDI(buffer: ArrayBuffer): ParsedEDILine[] {
  const workbook = XLSX.read(buffer, { type: 'array' });
  const sheetName = workbook.SheetNames[0];
  const sheet = workbook.Sheets[sheetName];
  const rows = XLSX.utils.sheet_to_json<Record<string, unknown>>(sheet, { defval: '' });

  const lines: ParsedEDILine[] = [];

  for (const row of rows) {
    const famille = String(row['Famille'] ?? '').trim();
    // Famille filtering moved to filterEDILines for category support

    const sign = String(row['Signe'] ?? '+').trim();
    if (sign === '-') continue;

    // ReSound: PrixUnitaireBrut is the invoiced unit price
    const priceRaw = row['PrixUnitaireBrut'];
    const unitPrice = typeof priceRaw === 'number' ? priceRaw : parseFloat(String(priceRaw).replace(',', '.'));
    if (isNaN(unitPrice) || unitPrice <= 0) continue;

    const discount = parseFloat(String(row['Remise%'] ?? '0').replace(',', '.')) || 0;
    const quantity = Number(row['Quantité']) || 1;

    // Apply discount to get actual invoiced unit price
    const actualPrice = discount > 0
      ? Math.round(unitPrice * (1 - discount / 100) * 100) / 100
      : Math.round(unitPrice * 100) / 100;

    // Skip free items (e.g. 100% discount)
    if (actualPrice <= 0) continue;

    lines.push({
      centre_code: String(row['CompteClient'] ?? '').trim(),
      // ReSound uses NomCentre (name-based, not numeric)
      centre_name: String(row['NomCentre'] ?? '').trim(),
      code_article: String(row['CodeArticle'] ?? '').trim(),
      description: String(row['DescriptionArticle'] ?? '').trim(),
      quantity,
      unit_price: actualPrice,
      discount_pct: discount,
      invoice_number: String(row['NuméroFacture'] ?? '').trim(),
      invoice_date: String(row['DateFacture'] ?? '').trim(),
      sign,
      famille,
    });
  }

  return lines;
}
