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

export const useStockStore = defineStore('inventoryStock', {
	state: () => ({
		/** @type {Array} List of stock 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 stock items with their variants.
		 */
		async fetchItems() {
			this.loading = true
			this.error = null

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

		/**
		 * Create a new stock item with variants.
		 */
		async createItem(data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/stock')
				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 Verkaufsmaterials'
				throw err
			} finally {
				this.loading = false
			}
		},

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

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/inventory/stock/${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 Verkaufsmaterials'
				throw err
			} finally {
				this.loading = false
			}
		},

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

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/inventory/stock/${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 Verkaufsmaterials'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Add a variant to an item.
		 */
		async addVariant(stockItemId, variantData) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/variants')
				const response = await axios.post(url, {
					stock_item_id: stockItemId,
					...variantData,
				})

				const item = this.items.find(i => i.id === stockItemId)
				if (item) {
					if (!item.variants) item.variants = []
					item.variants.push(response.data)
					item.total_amount = (item.total_amount || 0) + (response.data.amount || 0)
				}

				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen der Variante'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a variant.
		 */
		async deleteVariant(variantId, stockItemId) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/inventory/variants/${variantId}`)
				await axios.delete(url)

				const item = this.items.find(i => i.id === stockItemId)
				if (item && item.variants) {
					item.variants = item.variants.filter(v => v.id !== variantId)
				}
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Löschen der Variante'
				throw err
			} finally {
				this.loading = false
			}
		},

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

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