import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useFetch } from '@/composables/useFetch.ts'

export interface Project {
  id: number
  name: string
  description?: string
  key: string
}

export type CreateProjectDto = Partial<Pick<Project, 'name' | 'description'>>
export type UpdateProjectDto = Partial<Pick<Project, 'id' | 'name' | 'description'>>

export const useProjectsStore = defineStore('projects', () => {
  const projects = ref<Project[]>([])
  const project = ref<Project>()
  const { GET, POST, PUT, DELETE } = useFetch('/api/projects')

  async function findAll() {
    const response = await GET<Project[]>()
    if (response?.data) projects.value = response.data
  }

  async function findById(id: number) {
    const response = await GET<Project>({ param: id })
    if (response?.data) project.value = response.data
  }

  async function create({ name, description }: CreateProjectDto) {
    const response = await POST<Project>({ body: { name, description } })
    if (response?.data) projects.value.push(response.data)
  }

  async function update(id: number, { name, description }: CreateProjectDto) {
    const response = await PUT<Project>({ param: id, body: { name, description } })

    if (response?.data) {
      const index = projects.value.findIndex((el) => el.id === id)
      projects.value.splice(index, 1, response.data)
    }
  }

  async function remove(id: number) {
    const response = await DELETE<{ res: number }>({ param: id })

    if (response?.data) {
      const index = projects.value.findIndex((el) => el.id === id)
      projects.value.splice(index, 1)
    }
  }

  return { projects, findAll, findById, create, update, remove }
})
