function asString(value: unknown) {
  return typeof value === "string" ? value.trim() : ""
}

function applyTemplate(template: string, date: Date) {
  const year = String(date.getFullYear())
  const month = String(date.getMonth() + 1).padStart(2, "0")
  const monthName = new Intl.DateTimeFormat("fr-FR", { month: "long" }).format(date).toUpperCase()

  return template
    .replaceAll("{YYYY}", year)
    .replaceAll("{YY}", year.slice(-2))
    .replaceAll("{MM}", month)
    .replaceAll("{MONTH}", monthName)
}

function normalizeJoiner(prefix: string) {
  if (!prefix) {
    return ""
  }

  return /[/-]$/.test(prefix) ? prefix : `${prefix}/`
}

export function createQuoteReference(template?: string | null, createdAt?: Date) {
  const now = createdAt && !Number.isNaN(createdAt.getTime()) ? createdAt : new Date()
  const suffix = Math.random().toString(36).slice(2, 8).toUpperCase()
  const rawTemplate = asString(template)

  if (!rawTemplate) {
    return `DEV-${now.getUTCFullYear()}${String(now.getUTCMonth() + 1).padStart(2, "0")}${String(now.getUTCDate()).padStart(2, "0")}-${suffix}`
  }

  const prefix = applyTemplate(rawTemplate, now).trim()
  if (!prefix) {
    return suffix
  }

  return `${normalizeJoiner(prefix)}${suffix}`
}

