/**
 * Pinia store for Nextcloud Files integration state management.
 *
 * Handles member file browsing, folder creation, and file settings.
 *
 * Part of Issue #52.
 */
import { defineStore } from 'pinia'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

export const useFilesStore = defineStore('files', {
	state: () => ({
		/** @type {Array} List of files in current member folder */
		files: [],
		/** @type {boolean} Whether the member folder exists */
		folderExists: false,
		/** @type {string} Path to the member folder */
		folderPath: '',
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
		/** @type {Object} File integration settings */
		settings: {
			basePath: '/Verein/Mitglieder/',
			subfolderPattern: '{Nachname}_{Vorname}',
			autoCreate: false,
			lagerBasePath: '/Verein/Lager/',
		},
	}),

	actions: {
		/**
		 * Fetch files for a member's folder.
		 *
		 * @param {number} memberId - The member ID
		 */
		async fetchMemberFiles(memberId) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/members/${memberId}/files`)
				const response = await axios.get(url)

				this.files = response.data.files || []
				this.folderExists = response.data.exists || false
				this.folderPath = response.data.path || ''
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden der Dateien'
				console.error('Failed to fetch member files:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Ensure member folder exists (create if auto-create enabled).
		 *
		 * @param {number} memberId - The member ID
		 * @returns {boolean} Whether the folder now exists
		 */
		async ensureMemberFolder(memberId) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/members/${memberId}/files/ensure-folder`)
				const response = await axios.post(url)

				if (response.data.status === 'ok') {
					this.folderExists = true
					this.folderPath = response.data.path || ''
					// Refresh file list
					await this.fetchMemberFiles(memberId)
					return true
				}

				return false
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen des Ordners'
				console.error('Failed to ensure member folder:', err)
				return false
			} finally {
				this.loading = false
			}
		},

		/**
		 * Fetch file integration settings.
		 */
		async fetchSettings() {
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/files/settings')
				const response = await axios.get(url)
				this.settings = response.data
			} catch (err) {
				console.error('Failed to fetch file settings:', err)
			}
		},

		/**
		 * Update file integration settings.
		 *
		 * @param {Object} settings - The settings to update
		 */
		async updateSettings(settings) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/files/settings')
				const response = await axios.put(url, settings)
				this.settings = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Speichern der Einstellungen'
				console.error('Failed to update file settings:', err)
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Clear the current error.
		 */
		clearError() {
			this.error = null
		},
	},
})
