// Per-number delivery states (shared client/server).
//
// Moolre reports each message's delivery as a number but doesn't publish what
// the numbers mean, so an admin labels each one on /admin/settings. Until a
// number is labelled, numbers with it show as "sent" (accepted by Moolre),
// never as delivered or failed.

export type DeliveryLabel = 'delivered' | 'failed' | 'pending'

export const DELIVERY_LABELS: { value: DeliveryLabel; label: string; hint: string }[] = [
  { value: 'delivered', label: 'Delivered', hint: 'Reached the phone' },
  { value: 'pending', label: 'Still on its way', hint: 'Accepted, not confirmed yet' },
  { value: 'failed', label: 'Failed', hint: 'Will not reach the phone' },
]

// Moolre status numbers the settings page offers a label for.
export const DELIVERY_CODES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

export type RecipientState =
  | 'scheduled' // the send hasn't started
  | 'cancelled' // the scheduled send was cancelled
  | 'queued' // the send is under way and hasn't reached this number yet
  | 'not_sent' // Moolre refused this number's batch; its credits were refunded
  | 'sent' // accepted by Moolre, no delivery report (or an unlabelled one) yet
  | DeliveryLabel

// `code` is the stored Moolre status for this number (-1 = never sent).
export function recipientState(
  campaign: { status: string; sendProgress: number },
  index: number,
  code: number | undefined,
  labels: ReadonlyMap<number, DeliveryLabel>,
): RecipientState {
  if (campaign.status === 'scheduled') return 'scheduled'
  if (campaign.status === 'cancelled') return 'cancelled'
  if (code === -1) return 'not_sent'
  if (index >= campaign.sendProgress) return 'queued'
  if (code == null) return 'sent'
  return labels.get(code) ?? 'sent'
}

// Labelled delivered/failed numbers won't change, so they're not re-checked.
export function isFinalState(state: RecipientState) {
  return state === 'delivered' || state === 'failed' || state === 'not_sent' || state === 'cancelled'
}
