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

/**
 * Get selected category and service IDs from session storage.
 */
function getSelectedFilters() {
	const userAppointment = JSON.parse(sessionStorage.getItem("userAppointment")) || {};

	return {
		categories: (userAppointment.categories || []).map(Number),
		services: (userAppointment.services || []).map(Number),
	};
}

/**
 * Fetch all schedule posts from API.
 */
async function getSchedulePosts() {
	try {
		const data = await fetchUserData('ssas/v1/schedule', '');
		return Array.isArray(data) ? data : [];
	} catch (error) {
		console.error('Failed to fetch schedule posts:', error);
		return [];
	}
}

/**
 * Get unavailable dates based on selected categories and services.
 */
async function getNotAvailableDates() {
	const {
		categories: selectedCategories,
		services: selectedServices,
	} = getSelectedFilters();

	const schedulePosts = await getSchedulePosts();

	const notAvailableDates = [];

	for (const post of schedulePosts) {
		const postCategories = (post.categories || []).map((term) => Number(term.id));
		const postServices = (post.services || []).map((term) => Number(term.id));

		const categoryMatch =
			selectedCategories.length === 0 ||
			postCategories.some((id) => selectedCategories.includes(id));

		const serviceMatch =
			selectedServices.length === 0 ||
			postServices.some((id) => selectedServices.includes(id));

		// Match both filters (same logic as backend tax_query relation = AND)
		if (categoryMatch && serviceMatch) {
			if (Array.isArray(post.provider_availability)) {
				notAvailableDates.push(...post.provider_availability);
			}
		}
	}

	// Remove duplicate dates
	return [...new Set(notAvailableDates)];
}

export { getNotAvailableDates };