import { computed, ref } from 'vue'
import type { ExportField } from '../components/ExportFieldPanel.vue'

const normalizeSelection = (fields: ExportField[], selected: string[]) => {
  const requiredKeys = fields.filter((field) => field.required).map((field) => field.key)
  const merged = new Set([...requiredKeys, ...selected])
  return fields.map((field) => field.key).filter((key) => merged.has(key))
}

export const useExportFields = (fields: ExportField[], initialSelected: string[] = []) => {
  const selected = ref<string[]>(normalizeSelection(fields, initialSelected))
  const requiredKeys = computed(() => fields.filter((field) => field.required).map((field) => field.key))

  const setSelected = (next: string[]) => {
    selected.value = normalizeSelection(fields, next)
  }

  const toggle = (key: string, checked: boolean) => {
    if (requiredKeys.value.includes(key)) {
      setSelected(selected.value)
      return
    }
    const next = checked
      ? [...selected.value, key]
      : selected.value.filter((item) => item !== key)
    setSelected(next)
  }

  const selectAll = () => setSelected(fields.map((field) => field.key))
  const clearOptional = () => setSelected([])

  return {
    selected,
    requiredKeys,
    setSelected,
    toggle,
    selectAll,
    clearOptional
  }
}
