export interface Metadata {
	title: string;
	date: string;
	content: string;
	categories?: string[];
	section?: 'rants' | 'writes' | 'works';
}

export interface Post {
	meta: Metadata;
	path: string;
}

interface Data {
	metadata: Metadata;
}

function isData(obj: unknown): obj is Data {
	if (typeof obj !== 'object' || obj === null) {
		return false;
	}

	const dataObj = obj as Data;

	return (
		'metadata' in dataObj &&
		typeof dataObj.metadata.title === 'string' &&
		typeof dataObj.metadata.date === 'string'
	);
}

export const fetchMarkdownPosts = async (
	section: 'rants' | 'writes' | 'works'
): Promise<Post[]> => {
	let posts: Record<string, () => Promise<unknown>>;
	switch (section) {
		case 'rants':
			posts = import.meta.glob('/src/routes/rants/*.md');
			break;
		case 'writes':
			posts = import.meta.glob('/src/routes/writes/*.md');
			break;
		case 'works':
			posts = import.meta.glob('/src/routes/works/*.md');
			break;
		default:
			throw new Error('Could not find this section');
	}
	// const allPostFiles = import.meta.glob(`/src/routes/${section}/*.md`);
	const iterablePostFiles = Object.entries(posts);

	const allPosts = await Promise.all(
		iterablePostFiles.map(async ([path, resolver]) => {
			const data = await resolver();
			if (isData(data)) {
				const { metadata } = data;
				const postPath = path.slice(11, -3);
				return {
					meta: { ...metadata, section: section },
					path: postPath
				};
			} else {
				throw new Error('Could not properly parse this post');
			}
		})
	);

	return allPosts;
};
