import type { ResponsePublicSelectOption } from '~/api/response/response_public_select'
import type { TaskListItemData } from '~/api/response/response_task_list'

/**
 * 依 element_value_id 從 dateType 選項中找出對應的 value 顯示。
 * @param id - 訂單的 dateType（element_value_id，如 "60"）
 * @param options - dateType 選項陣列
 * @param locale - 語系，若有則優先匹配 language_code（如 "zh-Hant"）
 */
export function getDateTypeLabel(
  id: string,
  options: ResponsePublicSelectOption[] | undefined,
  locale?: string
): string {
  if (!id) return ''
  if (!options?.length) return id
  const matched = options.filter((o) => o.element_value_id === id)
  const byLocale = locale ? matched.find((o) => o.language_code === locale) : null
  return (byLocale ?? matched[0])?.value ?? id
}

/**
 * 從 task-list API 的 data 萃取 dateType 選項。
 * API 未回傳頂層 dateType，選項在 order.member.loverOption.dateType 與
 * order.lover[].lover.loverOption.dateType，合併後供 getDateTypeLabel 查找。
 */
export function extractDateTypeOptionsFromTaskList(
  list: TaskListItemData[]
): ResponsePublicSelectOption[] {
  const map = new Map<string, ResponsePublicSelectOption>()
  const add = (opts: ResponsePublicSelectOption[] | undefined) => {
    if (!Array.isArray(opts)) return
    for (const o of opts) {
      if (!map.has(o.element_value_id)) map.set(o.element_value_id, o)
    }
  }
  for (const order of list) {
    add(order.member?.loverOption?.dateType)
    for (const t of order.lover ?? []) {
      add(t.lover?.loverOption?.dateType)
    }
  }
  return Array.from(map.values())
}
