import 'package:pshared/data/dto/payment/operation.dart';
import 'package:pshared/data/dto/payment/operation_money.dart';
import 'package:pshared/data/mapper/money.dart';
import 'package:pshared/models/payment/execution_operation.dart';


extension PaymentOperationDTOMapper on PaymentOperationDTO {
  PaymentExecutionOperation toDomain() => PaymentExecutionOperation(
    stepRef: stepRef,
    operationRef: operationRef,
    gateway: gateway,
    code: code,
    state: state,
    label: label,
    money: money?.toDomain(),
    failureCode: failureCode,
    failureReason: failureReason,
    startedAt: _parseDateTime(startedAt),
    completedAt: _parseDateTime(completedAt),
  );
}

extension PaymentExecutionOperationMapper on PaymentExecutionOperation {
  PaymentOperationDTO toDTO() => PaymentOperationDTO(
    stepRef: stepRef,
    operationRef: operationRef,
    gateway: gateway,
    code: code,
    state: state,
    label: label,
    money: money?.toDTO(),
    failureCode: failureCode,
    failureReason: failureReason,
    startedAt: startedAt?.toUtc().toIso8601String(),
    completedAt: completedAt?.toUtc().toIso8601String(),
  );
}

extension PaymentOperationMoneyDTOMapper on PaymentOperationMoneyDTO {
  PaymentOperationMoney toDomain() => PaymentOperationMoney(
    planned: planned?.toDomain(),
    executed: executed?.toDomain(),
  );
}

extension PaymentOperationMoneyMapper on PaymentOperationMoney {
  PaymentOperationMoneyDTO toDTO() => PaymentOperationMoneyDTO(
    planned: planned?.toDTO(),
    executed: executed?.toDTO(),
  );
}

extension PaymentOperationMoneySnapshotDTOMapper
    on PaymentOperationMoneySnapshotDTO {
  PaymentOperationMoneySnapshot toDomain() => PaymentOperationMoneySnapshot(
    amount: amount?.toDomain(),
    convertedAmount: convertedAmount?.toDomain(),
  );
}

extension PaymentOperationMoneySnapshotMapper on PaymentOperationMoneySnapshot {
  PaymentOperationMoneySnapshotDTO toDTO() => PaymentOperationMoneySnapshotDTO(
    amount: amount?.toDTO(),
    convertedAmount: convertedAmount?.toDTO(),
  );
}

DateTime? _parseDateTime(String? value) {
  final normalized = value?.trim();
  if (normalized == null || normalized.isEmpty) return null;
  return DateTime.tryParse(normalized);
}
