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

export const useGeneralStore = defineStore('inventoryGeneral', {
	state: () => ({
		/** @type {Array} List of general material items */
		items: [],
		/** @type {string|null} Current search/filter text */
		searchText: '',
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	getters: {
		/**
		 * Filtered items based on search text.
		 */
		filteredItems: (state) => {
			if (!state.searchText) return state.items
			const lower = state.searchText.toLowerCase()
			return state.items.filter(item =>
				item.name.toLowerCase().includes(lower)
			)
		},
	},

	actions: {
		/**
		 * Fetch all general material items.
		 */
		async fetchItems() {
			this.loading = true
			this.error = null

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

		/**
		 * Create a new general material item.
		 */
		async createItem(data) {
			this.loading = true
			this.error = null

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

		/**
		 * Update an existing general material item.
		 */
		async updateItem(id, data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/inventory/general/${id}`)
				const response = await axios.put(url, data)
				const index = this.items.findIndex(i => i.id === id)
				if (index !== -1) {
					this.items[index] = response.data
				}
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Aktualisieren des Materials'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a general material item.
		 */
		async deleteItem(id) {
			this.loading = true
			this.error = null

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

		setSearchText(text) {
			this.searchText = text
		},

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