import { ComplianceStatus, type FormElementDto } from '~/.api-client'
import { complianceCheckableElementTypes, complianceMap } from './complianceMap'
import type { FormElementId } from '~/types/FormElement'

const formElementComplianceMap = ref(new Map<FormElementId, ComplianceStatus>())

export function useApplicationFormValidator() {
  function getHighestComplianceStatus(): ComplianceStatus {
    const complianceStatusValues = Array.from(formElementComplianceMap.value.values())
    const highestComplianceNumber = Math.max(
      ...complianceStatusValues.map((complianceStatus) => Object.values(ComplianceStatus).indexOf(complianceStatus))
    )
    return Object.values(ComplianceStatus)[highestComplianceNumber]
  }

  function validateFormElements(formElements: FormElementDto[]): Map<FormElementId, ComplianceStatus> {
    formElementComplianceMap.value.clear()

    formElements.forEach((formElement) => {
      if (!complianceCheckableElementTypes.includes(formElement.type)) return

      // Reset any previously set compliance status when all options are false
      const hasAtLeastOneOptionSet = formElement.options.some((option) => option.value && option.value !== 'false')
      if (!hasAtLeastOneOptionSet) {
        // No value set, continue with next form element
        return
      }

      formElement.options.forEach((option) => {
        if (!option.value) {
          console.log(`Value missing for ${formElement.type}`)
          return
        }

        // Value not set to true, continue with next option
        if (option.value === 'false') {
          return
        }

        const currentHighestComplianceStatus =
          complianceMap?.get(option.processingPurpose)?.get(option.employeeDataCategory) ?? ComplianceStatus.NonCritical
        const currentHighestComplianceStatusPos =
          Object.values(ComplianceStatus).indexOf(currentHighestComplianceStatus)

        if (formElementComplianceMap.value.has(formElement.id)) {
          const newComplianceStatus = formElementComplianceMap.value.get(formElement.id)!
          const newComplianceStatusPos = Object.values(ComplianceStatus).indexOf(newComplianceStatus)

          if (newComplianceStatusPos > currentHighestComplianceStatusPos) {
            formElementComplianceMap.value.set(formElement.id, newComplianceStatus)
          }
        } else {
          formElementComplianceMap.value.set(formElement.id, currentHighestComplianceStatus)
        }
      })
    })

    return formElementComplianceMap.value
  }

  return { getHighestComplianceStatus, validateFormElements }
}
