// SMS helpers shared between client and server.

// Characters in the GSM 03.38 basic set (plus extension table) keep a
// message in 160-character segments. Anything else switches to Unicode (70).
const GSM_BASIC =
  '@£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !"#¤%&\'()*+,-./0123456789:;<=>?¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑÜ§¿abcdefghijklmnopqrstuvwxyzäöñüà'
const GSM_EXTENDED = '^{}\\[~]|€'

export function countSegments(message: string) {
  let isGsm = true
  let length = 0
  for (const ch of message) {
    if (GSM_BASIC.includes(ch)) length += 1
    else if (GSM_EXTENDED.includes(ch)) length += 2
    else {
      isGsm = false
      break
    }
  }
  if (!isGsm) length = [...message].length
  const single = isGsm ? 160 : 70
  const multi = isGsm ? 153 : 67
  const segments = length === 0 ? 0 : length <= single ? 1 : Math.ceil(length / multi)
  return { length, segments, encoding: isGsm ? 'GSM-7' : 'Unicode', perSegment: segments > 1 ? multi : single }
}

// Normalizes Ghanaian numbers to international format without "+": 233XXXXXXXXX.
export function normalizeGhanaPhone(raw: string): string | null {
  const digits = raw.replace(/[^\d+]/g, '').replace(/^\+/, '')
  if (/^233\d{9}$/.test(digits)) return digits
  if (/^0\d{9}$/.test(digits)) return `233${digits.slice(1)}`
  if (/^\d{9}$/.test(digits)) return `233${digits}`
  return null
}

// Splits pasted text on commas, semicolons, whitespace and new lines.
export function parseRecipients(text: string) {
  const valid = new Set<string>()
  const invalid: string[] = []
  for (const token of text.split(/[\s,;]+/)) {
    if (!token) continue
    const phone = normalizeGhanaPhone(token)
    if (phone) valid.add(phone)
    else invalid.push(token)
  }
  return { valid: [...valid], invalid }
}

export const SENDER_ID_PATTERN = /^[A-Za-z0-9 ]{3,11}$/

// Trims and collapses repeated spaces so "My  Shop " and "My Shop" match.
export function normalizeSenderId(raw: string) {
  return raw.trim().replace(/\s+/g, ' ')
}
