/**
 * Pinia store for injury tracking state management.
 *
 * Part of Issue #57.
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useInjuryStore = defineStore('injuries', {
	state: () => ({
		/** @type {Array} List of injuries */
		injuries: [],
		/** @type {object|null} Currently selected injury */
		currentInjury: null,
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
		/** @type {string|null} Success message */
		success: null,
	}),

	actions: {
		/**
		 * Fetch injuries with optional filters.
		 */
		async fetchInjuries(params = {}) {
			this.loading = true
			this.error = null

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

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

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

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

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/injuries')
				const response = await axios.post(url, data)
				this.injuries.unshift(response.data)
				this.success = 'Verletzung erfolgreich dokumentiert'
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen der Verletzung'
				throw err
			} finally {
				this.loading = false
			}
		},

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

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

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

		/**
		 * Delete an injury.
		 */
		async deleteInjury(id) {
			this.error = null

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

		/**
		 * Add an involved member to an injury.
		 */
		async addInvolvedMember(injuryId, memberId) {
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/injuries/${injuryId}/involved`)
				await axios.post(url, { memberId })
				await this.fetchInjury(injuryId)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Hinzufügen des Beteiligten'
				throw err
			}
		},

		/**
		 * Remove an involved member from an injury.
		 */
		async removeInvolvedMember(injuryId, memberId) {
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/injuries/${injuryId}/involved/${memberId}`)
				await axios.delete(url)
				await this.fetchInjury(injuryId)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Entfernen des Beteiligten'
				throw err
			}
		},

		clearError() {
			this.error = null
		},

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