import 'package:flutter/material.dart';

import 'package:pshared/models/payment/operation.dart';
import 'package:pshared/models/payment/status.dart';


List<CurrencyTotal> aggregateCurrencyTotals(
  List<OperationItem> operations,
  DateTimeRange range,
) {
  final totals = <String, double>{};
  for (final operation in operations) {
    if (operation.status != OperationStatus.success) continue;
    if (_isUnknownDate(operation.date)) continue;
    if (operation.date.isBefore(range.start) ||
        operation.date.isAfter(range.end)) {
      continue;
    }
    final currency = _normalizeCurrency(operation.currency);
    totals[currency] = (totals[currency] ?? 0) + operation.amount;
  }

  final list = totals.entries
      .map((entry) => CurrencyTotal(entry.key, entry.value))
      .toList();
  list.sort((a, b) => a.currency.compareTo(b.currency));
  return list;
}

String _normalizeCurrency(String raw) {
  final trimmed = raw.trim();
  return trimmed.isEmpty ? '-' : trimmed;
}

bool _isUnknownDate(DateTime date) => date.millisecondsSinceEpoch == 0;

class CurrencyTotal {
  final String currency;
  final double amount;

  const CurrencyTotal(this.currency, this.amount);
}
