import { defineStore } from 'pinia'
import { nanoid } from 'nanoid'

export interface State {
  problems: ProblemState[]
  objectives: ObjectiveState[]
}

export interface ProblemState {
  id: string
  content: string
}

export interface ObjectiveState {
  id: string
  content: string
}

export const useObjectiveStore = defineStore('objective', {
  state: (): State => {
    return {
      problems: [{ id: nanoid(4), content: '' }],
      objectives: [{ id: nanoid(4), content: '' }]
    }
  },
  actions: {
    setData(data?: State) {
      if (!data?.problems) return
      this.setProblems(data.problems)
      this.setObjectives(data.objectives)
    },
    setProblems(list: ProblemState[]) {
      this.problems = list
    },
    addProblem(data: Omit<ProblemState, 'id'>) {
      this.problems.push({ id: nanoid(4), ...data })
    },
    updateProblem(data: ProblemState) {
      const index = this.problems.findIndex(item => item.id === data.id)
      this.problems[index] = data
    },
    removeProblem(id: string) {
      this.problems = this.problems.filter(item => item.id !== id)
    },

    setObjectives(list: ObjectiveState[]) {
      this.objectives = list
    },
    addObjective(data: Omit<ObjectiveState, 'id'>) {
      this.objectives.push({ id: nanoid(4), ...data })
    },
    updateObjective(data: ObjectiveState) {
      const index = this.objectives.findIndex(item => item.id === data.id)
      this.objectives[index] = data
    },
    removeObjective(id: string) {
      this.objectives = this.objectives.filter(item => item.id !== id)
    }
  }
})
