jQuery(document).ready(function ($) {
	$('#linksy-db-migrator').click(async function (e) {
		try {
			e.target.disabled = true

			const params = urlSearchParams({
				action: 'linksy_perform_database_migration',
				nonce: LINKSYAI_SAR_SECURE_TOKEN,
			})

			const {
				data: { data },
			} = await axios.post(ajaxurl, params)

			if (data.success) {
				window.location.reload()
			}
		} catch (error) {
			console.log(error.response?.data?.data || error.message)
		}
	})
})

function range(start, end) {
	return {
		[Symbol.iterator]: function () {
			return {
				current: start,
				last: end,
				next() {
					if (this.current <= this.last) {
						return { done: false, value: this.current++ }
					}
					return { done: true }
				},
			}
		},
	}
}

function generateRandomKey(prefix = null, length = 32) {
	const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
	let key = ''

	// generate random (length / 2) characters
	for (const num of range(0, Math.floor(length / 2))) {
		key += chars.charAt(Math.floor(Math.random() * chars.length))
	}

	// add the next (length / 2) characters from timestamp
	key += Date.now()
		.toString(16)
		.slice(0, Math.floor(length / 2))

	// add prefix if provided
	if (prefix) {
		key = prefix + key
	}

	return key
}

function unwrapTag(input) {
	const temp = document.createElement('div')
	temp.innerHTML = input

	if (temp.childNodes.length === 1 && temp.firstChild.nodeType === Node.ELEMENT_NODE) {
		return temp.firstChild.innerHTML
	}

	return input
}
