/**
 * Pinia store for inventory categories.
 *
 * Handles fetching and CRUD operations for inventory categories.
 *
 * Part of Issue #165 (Inventory Tracking).
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useCategoriesStore = defineStore('inventoryCategories', {
	state: () => ({
		/** @type {Array} List of categories */
		categories: [],
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	actions: {
		/**
		 * Fetch all categories.
		 */
		async fetchCategories() {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/categories')
				const response = await axios.get(url)
				this.categories = response.data.data || []
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden der Kategorien'
				console.error('Failed to fetch inventory categories:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Create a new category.
		 */
		async createCategory(name) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/categories')
				const response = await axios.post(url, { name })
				this.categories.push(response.data)
				this.categories.sort((a, b) => a.name.localeCompare(b.name))
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen der Kategorie'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a category.
		 */
		async deleteCategory(id) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/inventory/categories/${id}`)
				await axios.delete(url)
				this.categories = this.categories.filter(c => c.id !== id)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Löschen der Kategorie'
				throw err
			} finally {
				this.loading = false
			}
		},

		clearError() {
			this.error = null
		},
	},
})
