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

export const useAuditLogStore = defineStore('auditlog', {
	state: () => ({
		/** @type {Array} Audit log entries */
		entries: [],
		/** @type {number} Total entry count */
		total: 0,
		/** @type {boolean} Loading state */
		loading: false,
		/** @type {string|null} Error message */
		error: null,
		/** @type {number} Current offset */
		offset: 0,
		/** @type {number} Items per page */
		limit: 50,
		/** @type {Object} Active filters */
		filters: {
			entitaet: null,
			entitaetId: null,
			ncUserId: null,
			from: null,
			to: null,
		},
	}),

	getters: {
		hasMore: (state) => state.offset + state.limit < state.total,
		currentPage: (state) => Math.floor(state.offset / state.limit) + 1,
		totalPages: (state) => Math.ceil(state.total / state.limit),
	},

	actions: {
		/**
		 * Fetch audit log entries with current filters and pagination.
		 */
		async fetchEntries(offset = 0) {
			this.loading = true
			this.error = null
			this.offset = offset

			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/audit-log')
				const params = {
					limit: this.limit,
					offset: this.offset,
				}

				if (this.filters.entitaet) params.entitaet = this.filters.entitaet
				if (this.filters.entitaetId) params.entitaetId = this.filters.entitaetId
				if (this.filters.ncUserId) params.ncUserId = this.filters.ncUserId
				if (this.filters.from) params.from = this.filters.from
				if (this.filters.to) params.to = this.filters.to

				const response = await axios.get(url, { params })
				this.entries = response.data.data
				this.total = response.data.total
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden des Audit-Logs'
				console.error('Failed to fetch audit log:', err)
			} finally {
				this.loading = false
			}
		},

		/**
		 * Update filters and reload.
		 */
		async applyFilters(filters) {
			this.filters = { ...this.filters, ...filters }
			await this.fetchEntries(0)
		},

		/**
		 * Clear all filters and reload.
		 */
		async clearFilters() {
			this.filters = {
				entitaet: null,
				entitaetId: null,
				ncUserId: null,
				from: null,
				to: null,
			}
			await this.fetchEntries(0)
		},

		async goToPage(page) {
			const newOffset = (page - 1) * this.limit
			await this.fetchEntries(newOffset)
		},

		/**
		 * Change page size and reload from page 1.
		 */
		async setLimit(newLimit) {
			this.limit = newLimit
			await this.fetchEntries(0)
		},

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