import { ref } from 'vue'
import { defineStore } from 'pinia'

const upsert =
  (listRef) =>
  (entry, index = null) => {
    if (index == null || index < 0) {
      listRef.value = [...listRef.value, entry]
    } else {
      listRef.value = listRef.value.map((item, i) => (i === index ? entry : item))
    }
  }

export const useCompleteInfoStore = defineStore('missionaryCompleteInfo', () => {
  const introduction = ref('')
  const skills = ref([])
  const workExperiences = ref([])
  const educationHistory = ref([])
  const certificates = ref([])

  const reset = () => {
    introduction.value = ''
    skills.value = []
    workExperiences.value = []
    educationHistory.value = []
    certificates.value = []
  }

  // Keys mirror what POST /me/register-data persists — flat `{ key: value }`
  // where array values hold the section entries.
  const hydrateFromRegisterData = (data = {}) => {
    if (typeof data.introduction === 'string') introduction.value = data.introduction
    if (Array.isArray(data.skills)) skills.value = data.skills
    if (Array.isArray(data.workExperiences)) workExperiences.value = data.workExperiences
    if (Array.isArray(data.educationHistory)) educationHistory.value = data.educationHistory
    if (Array.isArray(data.certificates)) certificates.value = data.certificates
  }

  const addSkill = (skill) => {
    if (skills.value.some((s) => s.title === skill.title)) return
    skills.value = [...skills.value, skill]
  }

  const removeSkill = (title) => {
    skills.value = skills.value.filter((s) => s.title !== title)
  }

  const upsertWorkExperience = upsert(workExperiences)
  const upsertEducation = upsert(educationHistory)
  const upsertCertificate = upsert(certificates)

  const buildPayload = () => ({
    introduction: introduction.value,
    skills: skills.value,
    workExperiences: workExperiences.value,
    educationHistory: educationHistory.value,
    certificates: certificates.value,
  })

  return {
    introduction,
    skills,
    workExperiences,
    educationHistory,
    certificates,
    reset,
    hydrateFromRegisterData,
    addSkill,
    removeSkill,
    upsertWorkExperience,
    upsertEducation,
    upsertCertificate,
    buildPayload,
  }
})
