import 'package:pshared/data/dto/payment/endpoint.dart';
import 'package:pshared/data/dto/payment/response_endpoint.dart';
import 'package:pshared/data/mapper/payment/payment.dart';
import 'package:pshared/models/payment/endpoint.dart';
import 'package:pshared/models/payment/methods/data.dart';

extension PaymentResponseEndpointDTOMapper on PaymentResponseEndpointDTO {
  PaymentEndpoint toDomain() {
    final normalizedType = _normalize(type);
    final normalizedData = _cloneData(data);

    return PaymentEndpoint(
      method: _tryParseMethod(normalizedType, normalizedData),
      paymentMethodRef: _normalize(paymentMethodRef),
      payeeRef: _normalize(payeeRef),
      type: normalizedType,
      rawData: normalizedData,
    );
  }
}

extension PaymentEndpointMapper on PaymentEndpoint {
  PaymentResponseEndpointDTO toDTO() {
    final methodData = method;
    if (methodData != null) {
      final endpoint = methodData.toDTO();
      return PaymentResponseEndpointDTO(
        type: endpoint.type,
        data: endpoint.data,
        paymentMethodRef: _normalize(paymentMethodRef),
        payeeRef: _normalize(payeeRef),
      );
    }

    return PaymentResponseEndpointDTO(
      type: _normalize(type),
      data: _cloneData(rawData),
      paymentMethodRef: _normalize(paymentMethodRef),
      payeeRef: _normalize(payeeRef),
    );
  }
}

PaymentMethodData? _tryParseMethod(String? type, Map<String, dynamic>? data) {
  if (type == null || data == null) {
    return null;
  }

  try {
    return PaymentEndpointDTO(type: type, data: data).toDomain();
  } catch (_) {
    return null;
  }
}

String? _normalize(String? value) {
  final trimmed = value?.trim();
  if (trimmed == null || trimmed.isEmpty) return null;
  return trimmed;
}

Map<String, dynamic>? _cloneData(Map<String, dynamic>? data) {
  if (data == null) return null;
  if (data.isEmpty) return <String, dynamic>{};
  return Map<String, dynamic>.from(data);
}
