enum PaymentOrchestrationState {
  created,
  executing,
  needsAttention,
  settled,
  failed,
  unspecified,
}

PaymentOrchestrationState paymentOrchestrationStateFromValue(String? value) {
  final normalized = _normalizePaymentState(value);
  switch (normalized) {
    case 'CREATED':
    case 'ACCEPTED':
      return PaymentOrchestrationState.created;
    case 'EXECUTING':
    case 'PROCESSING':
    case 'FUNDS_RESERVED':
    case 'SUBMITTED':
      return PaymentOrchestrationState.executing;
    case 'NEEDS_ATTENTION':
      return PaymentOrchestrationState.needsAttention;
    case 'SETTLED':
    case 'SUCCESS':
      return PaymentOrchestrationState.settled;
    case 'FAILED':
    case 'CANCELLED':
      return PaymentOrchestrationState.failed;
    default:
      return PaymentOrchestrationState.unspecified;
  }
}

String paymentOrchestrationStateToValue(PaymentOrchestrationState state) {
  switch (state) {
    case PaymentOrchestrationState.created:
      return 'orchestration_state_created';
    case PaymentOrchestrationState.executing:
      return 'orchestration_state_executing';
    case PaymentOrchestrationState.needsAttention:
      return 'orchestration_state_needs_attention';
    case PaymentOrchestrationState.settled:
      return 'orchestration_state_settled';
    case PaymentOrchestrationState.failed:
      return 'orchestration_state_failed';
    case PaymentOrchestrationState.unspecified:
      return 'orchestration_state_unspecified';
  }
}

extension PaymentOrchestrationStateX on PaymentOrchestrationState {
  bool get isTerminal {
    switch (this) {
      case PaymentOrchestrationState.settled:
      case PaymentOrchestrationState.failed:
        return true;
      case PaymentOrchestrationState.created:
      case PaymentOrchestrationState.executing:
      case PaymentOrchestrationState.needsAttention:
      case PaymentOrchestrationState.unspecified:
        return false;
    }
  }

  bool get isPending => !isTerminal;
}

String _normalizePaymentState(String? value) {
  final trimmed = (value ?? '').trim().toUpperCase();
  if (trimmed.isEmpty) {
    return '';
  }

  if (trimmed.startsWith('ORCHESTRATION_STATE_')) {
    return trimmed.substring('ORCHESTRATION_STATE_'.length);
  }
  if (trimmed.startsWith('PAYMENT_STATE_')) {
    return trimmed.substring('PAYMENT_STATE_'.length);
  }
  return trimmed;
}
