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

export const usePermissionsStore = defineStore('permissions', {
	state: () => ({
		/** @type {Array} Permission records */
		permissions: [],
		/** @type {Array} Nextcloud users */
		users: [],
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
	}),

	actions: {
		/**
		 * Fetch all permissions.
		 */
		async fetchPermissions() {
			this.loading = true
			this.error = null

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

		/**
		 * Fetch Nextcloud users for the user picker.
		 */
		async fetchUsers() {
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/permissions/users')
				const response = await axios.get(url)
				this.users = response.data
			} catch (err) {
				console.error('Failed to fetch users:', err)
			}
		},

		/**
		 * Set permission for a user.
		 */
		async setPermission(ncUserId, level, allowedStufen, canSeeBanking) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/permissions/${ncUserId}`)
				const response = await axios.put(url, {
					level,
					allowedStufen,
					canSeeBanking,
				})

				// Update local state
				const index = this.permissions.findIndex(p => p.ncUserId === ncUserId)
				if (index !== -1) {
					this.permissions[index] = response.data
				} else {
					this.permissions.push(response.data)
				}

				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Setzen der Berechtigung'
				throw err
			} finally {
				this.loading = false
			}
		},

		/**
		 * Remove permission for a user.
		 */
		async removePermission(ncUserId) {
			this.loading = true
			this.error = null

			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/permissions/${ncUserId}`)
				await axios.delete(url)
				this.permissions = this.permissions.filter(p => p.ncUserId !== ncUserId)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Entfernen der Berechtigung'
				throw err
			} finally {
				this.loading = false
			}
		},

		clearError() {
			this.error = null
		},
	},
})
