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

export const useBackupStore = defineStore('backup', {
	state: () => ({
		backups: [],
		settings: { schedule: 'disabled', retentionCount: 10, hasPassword: false },
		loading: false,
		creating: false,
		restoring: false,
		updating: false,
		updateInfo: null,
		error: null,
		success: null,
	}),

	actions: {
		async fetchBackups() {
			this.loading = true
			this.error = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/backups')
				const response = await axios.get(url)
				this.backups = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden der Backups'
			} finally {
				this.loading = false
			}
		},

		async createBackup(password) {
			this.creating = true
			this.error = null
			this.success = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/backups')
				const response = await axios.post(url, { password: password || undefined })
				this.success = `Backup "${response.data.filename}" erstellt`
				await this.fetchBackups()
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Erstellen des Backups'
				throw err
			} finally {
				this.creating = false
			}
		},

		async restoreBackup(filename, password) {
			this.restoring = true
			this.error = null
			this.success = null
			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/backups/${filename}/restore`)
				const response = await axios.post(url, {
					confirm: true,
					password: password || undefined,
				})
				this.success = `Backup wiederhergestellt: ${response.data.totalRows} Zeilen in ${response.data.restoredTables} Tabellen`
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Wiederherstellen'
				throw err
			} finally {
				this.restoring = false
			}
		},

		async deleteBackup(filename) {
			this.error = null
			try {
				const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/backups/${filename}`)
				await axios.delete(url)
				this.backups = this.backups.filter(b => b.filename !== filename)
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Loeschen'
			}
		},

		downloadBackup(filename) {
			const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/backups/${filename}/download`)
			window.location.href = url
		},

		async fetchSettings() {
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/backups/settings')
				const response = await axios.get(url)
				this.settings = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Laden der Einstellungen'
			}
		},

		async updateSettings(data) {
			this.error = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/backups/settings')
				const response = await axios.put(url, data)
				this.settings = response.data
				this.success = 'Backup-Einstellungen gespeichert'
			} catch (err) {
				this.error = err.response?.data?.error || 'Fehler beim Speichern der Einstellungen'
			}
		},

		async checkForUpdate() {
			this.error = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/update/check')
				const response = await axios.get(url)
				this.updateInfo = response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Update-Check fehlgeschlagen'
			}
		},

		async installUpdate(force) {
			this.updating = true
			this.error = null
			this.success = null
			try {
				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/update/install')
				const response = await axios.post(url, { force: force || false })
				if (response.data.success) {
					this.success = response.data.message
					await this.checkForUpdate()
				} else {
					this.error = response.data.message
				}
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Update fehlgeschlagen'
				throw err
			} finally {
				this.updating = false
			}
		},

		async installManualUpdate(archiveFile, signatureFile) {
			this.updating = true
			this.error = null
			this.success = null
			try {
				const form = new FormData()
				form.append('archive', archiveFile)
				form.append('signature', signatureFile)

				const url = generateUrl('/apps/mitgliederverwaltung/api/v1/update/install-manual')
				const response = await axios.post(url, form, {
					headers: { 'Content-Type': 'multipart/form-data' },
				})
				if (response.data.success) {
					this.success = response.data.message
					await this.checkForUpdate()
				} else {
					this.error = response.data.message || 'Manuelles Update fehlgeschlagen'
				}
				return response.data
			} catch (err) {
				this.error = err.response?.data?.error || 'Manuelles Update fehlgeschlagen'
				throw err
			} finally {
				this.updating = false
			}
		},

		clearError() {
			this.error = null
		},

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