import type { WebhookDispatch } from '@platform-modules/billing'
import { parseOrderId } from '../charge-key.js'
import { settleCheckout } from '../settle.js'
import type { CheckoutDeps } from '../types.js'
import type { OrdersSchema } from '@platform-modules/commerce-orders'

export function makeSettlementDispatch<S extends OrdersSchema>(
  deps: CheckoutDeps<S>,
): WebhookDispatch {
  return async (event) => {
    if (event.kind !== 'settlement') {
      return
    }
    const orderId = parseOrderId(event.chargeKey)
    await settleCheckout(deps, orderId, event.providerRef, event.amount)
  }
}
