import { normalizeReference } from './reference'

export interface BankRow {
  date: string
  description: string
  amount: number // in pounds, positive for credits
  reference?: string
  raw: Record<string, string>
}

export interface MatchResult {
  bankRow: BankRow
  pledgeId: string | null
  pledgeReference: string | null
  confidence: 'exact' | 'partial' | 'amount_only' | 'none'
  matchedAmount: number
}

/**
 * Attempt to match a bank statement row against known pledge references
 */
export function matchBankRow(
  row: BankRow,
  pledgeRefs: Map<string, { id: string; amountPence: number }>
): MatchResult {
  const entries = Array.from(pledgeRefs.entries())

  // Strategy 1: exact reference match in ref field
  if (row.reference) {
    const normalized = normalizeReference(row.reference)
    for (const [ref, pledge] of entries) {
      if (normalizeReference(ref) === normalized) {
        return {
          bankRow: row,
          pledgeId: pledge.id,
          pledgeReference: ref,
          confidence: 'exact',
          matchedAmount: row.amount,
        }
      }
    }
  }

  // Strategy 2: reference found in description (not in dedicated ref field)
  const descNormalized = row.description.replace(/[\s]/g, '').toUpperCase()
  for (const [ref, pledge] of entries) {
    const refNorm = normalizeReference(ref)
    if (descNormalized.includes(refNorm)) {
      return {
        bankRow: row,
        pledgeId: pledge.id,
        pledgeReference: ref,
        confidence: 'partial',
        matchedAmount: row.amount,
      }
    }
  }

  // Strategy 3: partial reference match (at least the 4-char code portion)
  for (const [ref, pledge] of entries) {
    const parts = ref.split('-')
    const codePart = parts.length >= 2 ? parts[1] : ''
    if (codePart.length >= 4 && descNormalized.includes(codePart)) {
      return {
        bankRow: row,
        pledgeId: pledge.id,
        pledgeReference: ref,
        confidence: 'partial',
        matchedAmount: row.amount,
      }
    }
  }

  return {
    bankRow: row,
    pledgeId: null,
    pledgeReference: null,
    confidence: 'none',
    matchedAmount: row.amount,
  }
}

/**
 * Parse a CSV bank statement into BankRow[]
 * Handles common UK bank export formats
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function parseBankCsv(_csvData: string, _columnMapping?: {
  dateCol?: string
  descriptionCol?: string
  amountCol?: string
  creditCol?: string
  referenceCol?: string
}): BankRow[] {
  // Dynamic import handled at call site; this returns parsed rows
  // Caller should use papaparse to get rows, then pass here
  return [] // implemented in the API route with papaparse
}
