/**
 * Pinia store for Lager (camp) state management.
 *
 * Part of Issue #55.
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useLagerStore = defineStore('lager', {
	state: () => ({
		/** @type {Array} List of camps */
		camps: [],
		/** @type {object|null} Currently selected camp */
		currentCamp: null,
		/** @type {number|null} Year filter */
		filterYear: null,
		/** @type {number|null} Stufe filter */
		filterStufeId: null,
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
		/** @type {string|null} Success message */
		success: null,
	}),

	getters: {
		/**
		 * Available year options from loaded camps.
		 */
		availableYears: (state) => {
			const years = new Set()
			const currentYear = new Date().getFullYear()
			years.add(currentYear)
			years.add(currentYear - 1)

			for (const camp of state.camps) {
				if (camp.startdatum) {
					years.add(parseInt(camp.startdatum.substring(0, 4)))
				}
			}

			return [...years].sort((a, b) => b - a)
		},
	},

	actions: {
		/**
		 * Fetch camps with optional filters.
		 */
		async fetchCamps() {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/lager')
				const params = {}
				if (this.filterYear) params.year = this.filterYear
				if (this.filterStufeId) params.stufeId = this.filterStufeId

				const response = await axios.get(url, { params })
				this.camps = response.data.data || []
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden der Lager'
				console.error('Failed to fetch camps:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Fetch a single camp with full details.
		 */
		async fetchCamp(id) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${id}`)
				const response = await axios.get(url)
				this.currentCamp = response.data
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden des Lagers'
				console.error('Failed to fetch camp:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Create a new camp.
		 */
		async createCamp(data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/lager')
				const response = await axios.post(url, data)
				this.camps.unshift(response.data)
				this.success = 'Lager erfolgreich erstellt'
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen des Lagers'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Update an existing camp.
		 */
		async updateCamp(id, data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${id}`)
				const response = await axios.put(url, data)
				this.currentCamp = response.data

				const index = this.camps.findIndex(c => c.id === id)
				if (index !== -1) {
					this.camps[index] = response.data
				}
				this.success = 'Lager erfolgreich aktualisiert'
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Aktualisieren des Lagers'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a camp.
		 */
		async deleteCamp(id) {
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${id}`)
				await axios.delete(url)
				this.camps = this.camps.filter(c => c.id !== id)
				this.success = 'Lager erfolgreich gelöscht'
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Löschen des Lagers'
				throw err
			}
		},

		/**
		 * Add a participant to a camp.
		 */
		async addTeilnehmer(lagerId, memberId, rolle = 'Teilnehmer') {
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${lagerId}/teilnehmer`)
				await axios.post(url, { memberId, rolle })
				await this.fetchCamp(lagerId)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Hinzufügen des Teilnehmers'
				throw err
			}
		},

		/**
		 * Remove a participant from a camp.
		 */
		async removeTeilnehmer(lagerId, memberId) {
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${lagerId}/teilnehmer/${memberId}`)
				await axios.delete(url)
				await this.fetchCamp(lagerId)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Entfernen des Teilnehmers'
				throw err
			}
		},

		clearError() {
			this.error = null
		},

		clearSuccess() {
			this.success = null
		},
	},
})
