import { defineStore } from 'pinia'
import { schemaApi } from '../services/api'

export const useSchemasStore = defineStore('schemas', {
  state: () => ({
    schemas: [],
    loading: false,
    error: null,
  }),

  actions: {
    async fetchAll() {
      this.loading = true
      this.error = null
      try {
        this.schemas = await schemaApi.list()
      } catch (e) {
        this.error = e.message
      } finally {
        this.loading = false
      }
    },

    async get(id) {
      return schemaApi.get(id)
    },

    async create(data) {
      const result = await schemaApi.create(data)
      return result
    },

    async update(id, data) {
      const updated = await schemaApi.update(id, data)
      this.schemas = this.schemas.map((s) => (s.id === id ? updated : s))
      return updated
    },

    async remove(id) {
      await schemaApi.remove(id)
      this.schemas = this.schemas.filter((s) => s.id !== id)
    },
  },
})
