import fetchUserData from "./fetch-user-data";

const getCategory = async (ids, type) => {
	const terms = await fetchUserData(`ssas/v1/ssas_${type}`, "");
	const selectedTerms = [];

	terms.forEach((term) => {
		ids.forEach((id) => {
			if (term.id == id) {
				selectedTerms.push(term.name);
			}
		});
	});

	return selectedTerms;
};

/**
 * Returns the site's configured timezone if available.
 * Falls back to the browser's timezone.
 */
const getSiteTimezone = () => {
	if (
		typeof window !== "undefined" &&
		window.ssasSettings &&
		window.ssasSettings.timezone
	) {
		return window.ssasSettings.timezone;
	}

	return Intl.DateTimeFormat().resolvedOptions().timeZone;
};

/**
 * Converts a Date into YYYY-MM-DD using the configured timezone.
 */
const convertIndTimeZone = (date) => {
	const timezone = getSiteTimezone();

	const localDate = new Date(
		date.toLocaleString("en-US", {
			timeZone: timezone,
		})
	);

	const yyyy = localDate.getFullYear();
	const mm = String(localDate.getMonth() + 1).padStart(2, "0");
	const dd = String(localDate.getDate()).padStart(2, "0");

	return `${yyyy}-${mm}-${dd}`;
};

/**
 * Converts a date into a readable string using the configured timezone.
 */
const convertDate = (date) => {
	const timezone = getSiteTimezone();

	return new Date(date).toLocaleString("en-IN", {
		timeZone: timezone,
		weekday: "long",
		year: "numeric",
		month: "long",
		day: "numeric",
		hour: "2-digit",
		minute: "2-digit",
		hour12: true,
	});
};

/**
 * Formats only the date portion.
 */
function convertFormattedDate(selectedDate) {
	const timezone = getSiteTimezone();

	return new Date(selectedDate).toLocaleString("en-IN", {
		timeZone: timezone,
		weekday: "long",
		year: "numeric",
		month: "long",
		day: "numeric",
	});
}

/**
 * Formats only the time portion.
 */
function convertFormattedTime(selectedTime) {
	const timezone = getSiteTimezone();

	return new Date(selectedTime).toLocaleString("en-IN", {
		timeZone: timezone,
		hour: "2-digit",
		minute: "2-digit",
		hour12: true,
	});
}

/**
 * Combines a selected date and HH:mm:ss time into a formatted string.
 */
function getFormattedDate(selectedDate, selectedTime) {
	let date = selectedDate;

	if (typeof date === "string") {
		date = new Date(date);
	}

	if (!(date instanceof Date) || isNaN(date.getTime())) {
		return;
	}

	const [hours = 0, minutes = 0, seconds = 0] = selectedTime
		.split(":")
		.map(Number);

	const dateWithTime = new Date(
		date.getFullYear(),
		date.getMonth(),
		date.getDate(),
		hours,
		minutes,
		seconds
	);

	return convertDate(dateWithTime);
}

export {
	getCategory,
	convertDate,
	getFormattedDate,
	convertFormattedDate,
	convertFormattedTime,
	convertIndTimeZone,
};