import { BadRequestException } from '@nestjs/common';
import type { CashHolderType } from '../../entities/cash-held-movement.entity';

/** A cash holder at the destination — same shape as the MD collector. */
export interface CashHolder {
  holder_type: CashHolderType;
  collector_name?: string | null;
  supplier_id?: string | null;
  driver_id?: string | null;
}

export interface ResolvedCashHolder {
  holder_key: string;
  holder_type: CashHolderType;
  collector_name: string | null;
  supplier_id: string | null;
  driver_id: string | null;
}

/** Collapse spacing + case so "Ravi  K" and "ravi k" are one holder. */
export function normaliseName(name: string): string {
  return name.trim().replace(/\s+/g, ' ');
}

/**
 * Stable key for a holder: OWN:<lower name> or SUPPLIER:<supplier>:<driver>.
 * Balances are grouped by this key + currency.
 */
export function cashHolderKey(h: CashHolder): ResolvedCashHolder {
  if (h.holder_type === 'OWN') {
    const name = normaliseName(h.collector_name ?? '');
    if (!name) throw new BadRequestException('Own staff name is required');
    return {
      holder_key: `OWN:${name.toLowerCase()}`,
      holder_type: 'OWN',
      collector_name: name,
      supplier_id: null,
      driver_id: null,
    };
  }
  if (h.holder_type === 'SUPPLIER') {
    if (!h.supplier_id || !h.driver_id) {
      throw new BadRequestException('Supplier and driver are required');
    }
    return {
      holder_key: `SUPPLIER:${h.supplier_id}:${h.driver_id}`,
      holder_type: 'SUPPLIER',
      collector_name: null,
      supplier_id: h.supplier_id,
      driver_id: h.driver_id,
    };
  }
  throw new BadRequestException('Unknown holder type');
}
