import type { HospitalsPageFormStateShape } from "@/lib/pages/hospitals-page/form-types"

type UnknownRecord = Record<string, unknown>

const SHARED_IMAGE_KEYS = new Set(["image", "logo", "imagePublicId"])

function isRecord(value: unknown): value is UnknownRecord {
  return value !== null && typeof value === "object" && !Array.isArray(value)
}

function normalizeImagesForLocale(targetNode: unknown, englishNode: unknown): unknown {
  if (Array.isArray(targetNode)) {
    return targetNode.map((item, index) =>
      normalizeImagesForLocale(item, Array.isArray(englishNode) ? englishNode[index] : undefined)
    )
  }
  if (!isRecord(targetNode)) return targetNode

  const result: UnknownRecord = { ...targetNode }
  const englishRecord = isRecord(englishNode) ? englishNode : {}

  for (const [key, value] of Object.entries(result)) {
    const englishValue = englishRecord[key]
    if (typeof value === "string" && SHARED_IMAGE_KEYS.has(key)) {
      const current = value.trim()
      const fallback = typeof englishValue === "string" ? englishValue.trim() : ""
      result[key] = current || fallback
      continue
    }
    if (Array.isArray(value) || isRecord(value)) {
      result[key] = normalizeImagesForLocale(value, englishValue)
    }
  }

  return result
}

export function normalizeHospitalsPageLocaleImagesForStorage(
  locales: Partial<Record<string, HospitalsPageFormStateShape>>
): Partial<Record<string, HospitalsPageFormStateShape>> {
  const english = locales.en
  if (!english) return locales

  const result: Partial<Record<string, HospitalsPageFormStateShape>> = { ...locales }
  for (const [code, state] of Object.entries(locales)) {
    if (!state) continue
    if (code === "en") {
      result[code] = state
      continue
    }
    result[code] = normalizeImagesForLocale(state, english) as HospitalsPageFormStateShape
  }
  return result
}
