export class RefundExceedsPaidError extends Error {
  override readonly name = 'RefundExceedsPaidError'
  readonly code = 'REFUND_EXCEEDS_PAID' as const
  readonly httpStatus = 422 as const

  constructor(
    message: string,
    readonly context: { chargeKey: string; amount: number },
  ) {
    super(message)
  }
}

/**
 * `settleCharge` found a durable `pending` charge intent already owning this
 * chargeKey — a concurrent in-flight attempt or a prior crash (floor #6). This
 * call does NOT charge again (a re-charge risks a double-charge: provider dedup
 * windows may be short). Recovery is `reconcileCharge`, driven by the
 * host's `listUnsettledIntents` sweep. 409 = the in-flight conflict.
 */
export class ChargeIntentPendingError extends Error {
  override readonly name = 'ChargeIntentPendingError'
  readonly code = 'CHARGE_INTENT_PENDING' as const
  readonly httpStatus = 409 as const

  constructor(readonly chargeKey: string) {
    super(
      `a charge intent for "${chargeKey}" is already in-flight or stuck pending; ` +
        'reconcile it (do not re-charge)',
    )
  }
}

export class WebhookVerificationError extends Error {
  override readonly name = 'WebhookVerificationError'
  readonly code = 'WEBHOOK_VERIFICATION_FAILED' as const
  readonly httpStatus = 400 as const

  constructor(message: string) {
    super(message)
  }
}

export class InvalidAmountError extends Error {
  override readonly name = 'InvalidAmountError'
  readonly code = 'INVALID_AMOUNT' as const
  readonly httpStatus = 422 as const

  constructor(
    message: string,
    readonly context: { value: number | string; field?: string },
  ) {
    super(message)
  }
}

export class RefundFailedError extends Error {
  override readonly name = 'RefundFailedError'
  readonly code = 'REFUND_FAILED' as const
  readonly httpStatus = 502 as const

  constructor(readonly context: { chargeKey: string; providerRef: string; status: string }) {
    super(
      `refund ${context.providerRef} for "${context.chargeKey}" failed: status=${context.status}`,
    )
  }
}

export class InvalidKeyComponentError extends Error {
  override readonly name = 'InvalidKeyComponentError'
  readonly code = 'INVALID_KEY_COMPONENT' as const
  readonly httpStatus = 422 as const

  constructor(
    message: string,
    readonly context: { field: string; value: string },
  ) {
    super(message)
  }
}
