/**
 * Subscription webhook idempotency — mirrors payment session settle guard pattern.
 * Processed event ids are stored in KV to skip duplicate activateSubscription runs.
 */

const KV_PREFIX = 'sub-webhook:'
/** 30 days — long enough to cover provider retry windows */
export const SUBSCRIPTION_WEBHOOK_IDEM_TTL_SEC = 60 * 60 * 24 * 30

export async function sha256Hex(data: string): Promise<string> {
  const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(data))
  return Array.from(new Uint8Array(buf))
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('')
}

export function subscriptionWebhookIdemKey(eventId: string): string {
  return `${KV_PREFIX}${eventId}`
}

export async function resolveSubscriptionWebhookEventId(
  event: { type: string; eventId?: string },
  rawBody: string,
): Promise<string> {
  if (event.eventId) return event.eventId
  return sha256Hex(`${event.type}:${rawBody}`)
}

export async function isSubscriptionWebhookDuplicate(
  kv: KVNamespace,
  eventId: string,
): Promise<boolean> {
  const key = subscriptionWebhookIdemKey(eventId)
  const existing = await kv.get(key)
  return existing != null
}

export async function markSubscriptionWebhookProcessed(
  kv: KVNamespace,
  eventId: string,
): Promise<void> {
  await kv.put(subscriptionWebhookIdemKey(eventId), '1', {
    expirationTtl: SUBSCRIPTION_WEBHOOK_IDEM_TTL_SEC,
  })
}
