/**
 * Pinia store for visual query builder state management.
 *
 * Handles saved queries CRUD, ad-hoc query execution, and available fields.
 *
 * Part of Issue #53.
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useQueriesStore = defineStore('queries', {
	state: () => ({
		/** @type {Array} List of saved queries */
		savedQueries: [],
		/** @type {Array} Available query fields metadata */
		fields: [],
		/** @type {Array} Current query results */
		results: [],
		/** @type {number} Total result count */
		total: 0,
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	actions: {
		/**
		 * Fetch available query fields.
		 */
		async fetchFields() {
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/queries/fields')
				const response = await axios.get(url)
				this.fields = response.data.data || []
			} catch (err) {
				console.error('Failed to fetch query fields:', err)
			}
		},

		/**
		 * Fetch all saved queries.
		 */
		async fetchSavedQueries() {
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/queries')
				const response = await axios.get(url)
				this.savedQueries = response.data.data || []
			} catch (err) {
				console.error('Failed to fetch saved queries:', err)
			}
		},

		/**
		 * Save a new query.
		 *
		 * @param {string} name - Query name
		 * @param {Object} queryJson - The query AST
		 * @param {Array|null} sortJson - Sort configuration
		 */
		async saveQuery(name, queryJson, sortJson = null) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/queries')
				const response = await axios.post(url, { name, queryJson, sortJson })
				this.savedQueries.push(response.data)
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Speichern der Abfrage'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Update an existing saved query.
		 *
		 * @param {number} id - Query ID
		 * @param {Object} data - Fields to update
		 */
		async updateQuery(id, data) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/queries/${id}`)
				const response = await axios.put(url, data)
				const idx = this.savedQueries.findIndex(q => q.id === id)
				if (idx !== -1) {
					this.savedQueries[idx] = response.data
				}
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Aktualisieren der Abfrage'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Delete a saved query.
		 *
		 * @param {number} id - Query ID
		 */
		async deleteQuery(id) {
			this.loading = true
			this.error = null

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

		/**
		 * Execute a saved query.
		 *
		 * @param {number} id - Query ID
		 */
		async executeSavedQuery(id) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/queries/${id}/execute`)
				const response = await axios.post(url)
				this.results = response.data.data || []
				this.total = response.data.total || 0
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Ausführen der Abfrage'
				console.error('Failed to execute saved query:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Execute an ad-hoc query.
		 *
		 * @param {Object} queryJson - The query AST
		 * @param {Array|null} sortJson - Sort configuration
		 */
		async executeAdHoc(queryJson, sortJson = null) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/queries/execute')
				const response = await axios.post(url, { queryJson, sortJson })
				this.results = response.data.data || []
				this.total = response.data.total || 0
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Ausführen der Abfrage'
				console.error('Failed to execute ad-hoc query:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Clear results.
		 */
		clearResults() {
			this.results = []
			this.total = 0
			this.error = null
		},
	},
})
