import { defineStore } from 'pinia'
import type { ZoneCharacter, Zone } from '@/types'

export const useZoneStore = defineStore('zone', {
  state: () => {
    return {
      zone: null as Zone | null,
      characters: [] as ZoneCharacter[],
      characterLoaded: false
    }
  },
  getters: {
    getCharacterById: (state) => {
      return (id: number) => state.characters.find((char) => char.character.id === id)
    },
    getCharacterCount: (state) => {
      return state.characters.length
    },
    isZoneSet: (state) => {
      return state.zone !== null
    }
  },
  actions: {
    setZone(zone: Zone | null) {
      this.zone = zone
    },
    setCharacters(characters: ZoneCharacter[]) {
      this.characters = characters
    },
    addCharacter(character: ZoneCharacter) {
      this.characters.push(character)
    },
    updateCharacter(updatedCharacter: ZoneCharacter) {
      const index = this.characters.findIndex((char) => char.character.id === updatedCharacter.character.id)
      if (index !== -1) this.characters[index] = updatedCharacter
    },
    removeCharacter(characterId: number) {
      this.characters = this.characters.filter((char) => char.character.id !== characterId)
    },
    setCharacterLoaded(loaded: boolean) {
      this.characterLoaded = loaded
    },
    reset() {
      this.zone = null
      this.characters = []
      this.characterLoaded = false
    }
  }
})
