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

export const useInventoryReportsStore = defineStore('inventoryReports', {
	state: () => ({
		/** @type {object|null} Condition report data */
		conditionReport: null,
		/** @type {object|null} Sales report data */
		salesReport: null,
		/** @type {boolean} Loading state for condition report */
		conditionLoading: false,
		/** @type {boolean} Loading state for sales report */
		salesLoading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	actions: {
		/**
		 * Fetch condition report data.
		 */
		async fetchConditionReport() {
			this.conditionLoading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/reports/condition')
				const response = await axios.get(url)
				this.conditionReport = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden des Materialzustandsberichts'
				console.error('Failed to fetch condition report:', err)
			} finally {
				this.conditionLoading = false
			}
		},

		/**
		 * Fetch sales report data with optional date range.
		 */
		async fetchSalesReport(dateFrom, dateTo) {
			this.salesLoading = true
			this.error = null

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

				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/inventory/reports/sales')
				const response = await axios.get(url, { params })
				this.salesReport = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden des Inventur-Verkaufsberichts'
				console.error('Failed to fetch sales report:', err)
			} finally {
				this.salesLoading = false
			}
		},

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