import type { FormulaireChamp } from "@/shared/types/formulaire"

// Helper to get fields within a section
export const getSectionFields = (sectionId: string, allFields: FormulaireChamp[]) => {
  const section = allFields.find((field) => field.id === sectionId)
  if (!section || !section.childFields) return []

  return section.childFields
    .map((fieldId) => allFields.find((field) => field.id === fieldId))
    .filter(Boolean) as FormulaireChamp[]
}

// Helper to get fields that are not in any section
export const getUnsectionedFields = (allFields: FormulaireChamp[]) => {
  // Collect all field IDs that are part of a section
  const sectionedFieldIds = allFields
    .filter((field) => field.type === "section")
    .flatMap((section) => section.childFields || [])

  // Return fields that are not in any section and are not sections themselves
  return allFields.filter((field) => field.type !== "section" && !sectionedFieldIds.includes(field.id))
}

// Get all section fields
export const getSections = (allFields: FormulaireChamp[]) => {
  return allFields.filter((field) => field.type === "section")
}

// Check if a field should be visible based on conditional logic
export const isFieldVisible = (field: FormulaireChamp, formValues: Record<string, any>): boolean => {
  if (!field.conditionalLogic?.dependsOn) return true

  const { dependsOn, showWhen } = field.conditionalLogic
  const dependsOnValue = formValues[dependsOn]

  if (!showWhen) return true

  const { operator, value } = showWhen

  switch (operator) {
    case "equals":
      return dependsOnValue === value
    case "notEquals":
      return dependsOnValue !== value
    case "contains":
      return dependsOnValue?.includes(value)
    case "greaterThan":
      return Number(dependsOnValue) > Number(value)
    case "lessThan":
      return Number(dependsOnValue) < Number(value)
    default:
      return true
  }
}
