import 'package:collection/collection.dart';

import 'package:pshared/data/mapper/payment/method.dart';
import 'package:pshared/models/payment/methods/data.dart';
import 'package:pshared/models/payment/type.dart';
import 'package:pshared/models/recipient/payment_method_draft.dart';


class RecipientMethodSnapshot {
  final PaymentType type;
  final String? existingId;
  final Map<String, dynamic>? data;
  final Map<String, String>? metadata;

  static final DeepCollectionEquality _mapEquality =
      const DeepCollectionEquality();

  const RecipientMethodSnapshot({
    required this.type,
    required this.existingId,
    required this.data,
    required this.metadata,
  });

  factory RecipientMethodSnapshot.fromDraft(RecipientMethodDraft draft) {
    return RecipientMethodSnapshot(
      type: draft.type,
      existingId: draft.existing?.id,
      data: _dataToSnapshot(draft.data),
      metadata: _metadataToSnapshot(draft.data),
    );
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is RecipientMethodSnapshot &&
        other.type == type &&
        other.existingId == existingId &&
        _mapEquality.equals(other.data, data) &&
        _mapEquality.equals(other.metadata, metadata);
  }

  @override
  int get hashCode => Object.hash(
        type,
        existingId,
        _mapEquality.hash(data),
        _mapEquality.hash(metadata),
      );
}

Map<String, dynamic>? _dataToSnapshot(PaymentMethodData? data) {
  if (data == null) return null;
  return data.toJsonMap();
}

Map<String, String>? _metadataToSnapshot(PaymentMethodData? data) {
  final metadata = data?.metadata;
  if (metadata == null) return null;
  return Map<String, String>.from(metadata);
}
