import 'package:money2/money2.dart';

import 'package:pshared/models/currency.dart';


final Currency _usdtCurrency = Currency.create(
  'USDT',
  6,
  symbol: '₮',
  isIso: false,
  country: 'Digital',
  unit: 'Tether',
  name: 'Tether',
);

final Currency _usdcCurrency = Currency.create(
  'USDC',
  6,
  symbol: r'($)',
  isIso: false,
  country: 'Digital',
  unit: 'USD Coin',
  name: 'USD Coin',
);

final Map<String, Currency> _commonCurrenciesByCode =
    <String, Currency>{
      for (final currency in CommonCurrencies().asList())
        currency.isoCode: currency,
      _usdtCurrency.isoCode: _usdtCurrency,
      _usdcCurrency.isoCode: _usdcCurrency,
    };

String currencyCodeToSymbol(CurrencyCode currencyCode) {
  final symbol = currencySymbolFromCode(currencyCodeToString(currencyCode));
  if (symbol == null || symbol.trim().isEmpty) {
    return currencyCodeToString(currencyCode);
  }
  return symbol;
}

String currencyToString(CurrencyCode currencyCode, double amount) {
  final code = currencyCodeToString(currencyCode);
  final currency = money2CurrencyFromCode(code);
  if (currency == null) {
    return '$amount $code';
  }
  final money = Money.fromNumWithCurrency(amount, currency);
  return money.toString();
}

CurrencyCode currencyStringToCode(String currencyCode) {
  final normalized = currencyCode.trim().toUpperCase();
  for (final value in CurrencyCode.values) {
    if (currencyCodeToString(value) == normalized) {
      return value;
    }
  }

  throw ArgumentError('Unknown currency code: $currencyCode');
}

String currencyCodeToString(CurrencyCode currencyCode) {
  return currencyCode.name.toUpperCase();
}

String? currencySymbolFromCode(String? code) {
  final currency = money2CurrencyFromCode(code);
  if (currency == null) return null;
  final symbol = currency.symbol.trim();
  return symbol.isEmpty ? null : symbol;
}

Currency? money2CurrencyFromCode(String? code) {
  final normalized = code?.trim().toUpperCase();
  if (normalized == null || normalized.isEmpty) return null;
  return _commonCurrenciesByCode[normalized] ?? Currencies().find(normalized);
}
