/**
 * Pinia store for calendar sync state management.
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useCalendarStore = defineStore('calendar', {
	state: () => ({
		status: null,
		syncing: false,
		enablingApp: false,
		error: null,
		success: null,
	}),

	actions: {
		async fetchStatus() {
			this.error = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/calendar/status')
				const response = await axios.get(url)
				this.status = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden des Kalender-Status'
			}
		},

		async triggerSync() {
			this.syncing = true
			this.error = null
			this.success = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/calendar/sync')
				const response = await axios.post(url)
				const stats = response.data
				const parts = []
				if (stats.created > 0) parts.push(`${stats.created} erstellt`)
				if (stats.updated > 0) parts.push(`${stats.updated} aktualisiert`)
				if (stats.deleted > 0) parts.push(`${stats.deleted} geloescht`)
				if (stats.juleica > 0) parts.push(`${stats.juleica} Juleica-Erinnerungen`)
				this.success = parts.length > 0
					? `Synchronisation abgeschlossen: ${parts.join(', ')}`
					: 'Synchronisation abgeschlossen — keine Aenderungen'
				await this.fetchStatus()
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler bei der Kalender-Synchronisation'
			} finally {
				this.syncing = false
			}
		},

		async enableCalendarApp() {
			this.enablingApp = true
			this.error = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/calendar/enable-app')
				const response = await axios.post(url)
				this.success = response.data.message
				await this.fetchStatus()
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Aktivieren der Calendar-App'
			} finally {
				this.enablingApp = false
			}
		},

		clearError() {
			this.error = null
		},

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