import 'package:money2/money2.dart';
import 'package:pshared/utils/currency.dart';

const String _decimalMoneyPattern = '0.##################';

Money? parseMoneyWithCurrency(String? amount, Currency? currency) {
  if (currency == null) return null;
  final value = _normalizeMoneyAmount(amount);
  if (value == null || value.isEmpty) return null;

  try {
    return Money.parseWithCurrency(
      value,
      currency,
      pattern: _decimalMoneyPattern,
    );
  } catch (_) {
    return null;
  }
}

Money? parseMoneyWithCurrencyCode(String? amount, String? currencyCode) {
  return parseMoneyWithCurrency(amount, money2CurrencyFromCode(currencyCode));
}

String? _normalizeMoneyAmount(String? value) {
  final normalized = value?.trim();
  if (normalized == null || normalized.isEmpty) return null;

  if (normalized.contains(',') && !normalized.contains('.')) {
    return normalized.replaceAll(',', '.');
  }

  return normalized;
}
