/**
 * Pinia store for inventory sales records.
 *
 * Handles fetching, creating, and filtering sales records.
 *
 * Part of Issue #165 (Inventory Tracking).
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useSalesStore = defineStore('inventorySales', {
	state: () => ({
		/** @type {Array} List of sales records */
		sales: [],
		/** @type {string|null} Filter from date */
		filterDateFrom: null,
		/** @type {string|null} Filter to date */
		filterDateTo: null,
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	getters: {
		/**
		 * Filtered sales based on date range.
		 */
		filteredSales: (state) => {
			if (!state.filterDateFrom && !state.filterDateTo) {
				return state.sales
			}
			return state.sales.filter(sale => {
				const saleDate = sale.date
				if (state.filterDateFrom && saleDate < state.filterDateFrom) {
					return false
				}
				if (state.filterDateTo && saleDate > state.filterDateTo) {
					return false
				}
				return true
			})
		},
	},

	actions: {
		/**
		 * Fetch sales records with optional date filter.
		 */
		async fetchSales() {
			this.loading = true
			this.error = null

			try {
				const params = {}
				if (this.filterDateFrom) params.dateFrom = this.filterDateFrom
				if (this.filterDateTo) params.dateTo = this.filterDateTo

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

		/**
		 * Create a new sale record.
		 */
		async createSale(data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/sales')
				const response = await axios.post(url, data)
				this.sales.unshift(response.data)
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen des Verkaufs'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a sale record.
		 */
		async deleteSale(id) {
			this.loading = true
			this.error = null

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

		setFilterDateFrom(date) {
			this.filterDateFrom = date
		},

		setFilterDateTo(date) {
			this.filterDateTo = date
		},

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