/**
 * To add validations to localStorage operations.
 */

import { isTargetData, isTargetMode, TargetData, TargetMode } from "../types/addInTypes";

/**
 * Retrieves the current target mode from local storage.
 *
 * @returns {TargetMode} The target mode stored in local storage, or "default" if not set.
 * @throws {Error} If the retrieved value is not a valid TargetMode.
 */
export const getTargetMode = (): TargetMode => {
	const targetMode: TargetMode|string|null = localStorage.getItem("targetMode");
	if (!targetMode) return "default";
	if (!isTargetMode(targetMode)) throw new Error("Invalid value retrieved for 'targetMode'.");
	return targetMode;
}

/**
 * Sets the target mode in local storage after validating the provided mode.
 *
 * @param mode - The target mode to be set. Must pass the `isTargetMode` check.
 * @throws {Error} Throws an error if the provided mode is not a valid `TargetMode`.
 */
export const setTargetMode = (mode:TargetMode) => {
	if (!isTargetMode(mode)) throw new Error("Invalid value to set for 'targetMode'.");
	localStorage.setItem("targetMode", mode);
}

/**
 * Retrieves and parses the target data from localStorage for the specified mode.
 *
 * @param mode - The mode used to determine the key for retrieving target data from localStorage.
 * @returns The parsed and validated TargetData object.
 * @throws {Error} If the retrieved value is not valid JSON or does not conform to the TargetData type.
 */
export const getTargetData = (mode:TargetMode): TargetData => {
	const targetDataStr = localStorage.getItem(`${mode}TargetData`);
	let targetData = null
	try {
		targetData = JSON.parse(targetDataStr);
		if (!isTargetData(targetData)) throw new Error('Invalid')
	} catch (e:any) {
		throw new Error('Gotten value for target data is not valid. Make sure to properly set it before retrieving it.')
	}
	return targetData;
}

/**
 * Stores the provided target data in localStorage under a key based on the given mode.
 *
 * @param mode - The target mode used to determine the storage key. Must be a valid TargetMode.
 * @param data - The target data to store. Must be a valid TargetData object.
 * @throws {Error} If the provided mode is not valid.
 * @throws {Error} If the provided data is not valid.
 */
export const setTargetData = (mode:TargetMode, data:TargetData) => {
	if (!isTargetMode(mode)) throw new Error('Target mode provided is not valid');
	if (!isTargetData(data)) throw new Error('Target data provided is not valid');

	localStorage.setItem(`${mode}TargetData`, JSON.stringify(data));
}