import { user } from '$lib/config';
import { parseFrontmatter } from './frontmatter';
import { renderMarkdown } from './markdown';

export interface BlogPost {
	slug: string;
	title: string;
	author: string;
	date: string;
	tags: string[];
	excerpt: string;
	html: string;
	readingTime: number;
}

const postFiles = import.meta.glob('/blogs/*.md', {
	eager: true,
	query: '?raw',
	import: 'default'
}) as Record<string, string>;

function slugFromPath(path: string): string {
	return path.split('/').pop()!.replace(/\.md$/, '');
}

function estimateReadingTime(content: string): number {
	const words = content.trim().split(/\s+/).filter(Boolean).length;
	return Math.max(1, Math.round(words / 200));
}

function buildPost(path: string, raw: string): BlogPost {
	const { data, content } = parseFrontmatter(raw);
	const slug = slugFromPath(path);

	return {
		slug,
		title: (data.title as string) || slug,
		author: (data.author as string) || user.displayname,
		date: (data.date as string) || '',
		tags: (data.tags as string[]) || [],
		excerpt: (data.excerpt as string) || '',
		html: renderMarkdown(content),
		readingTime: estimateReadingTime(content)
	};
}

const allPosts: BlogPost[] = Object.entries(postFiles)
	.map(([path, raw]) => buildPost(path, raw))
	.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));

export function getAllPosts(): BlogPost[] {
	return allPosts;
}

export function getPostBySlug(slug: string): BlogPost | undefined {
	return allPosts.find((post) => post.slug === slug);
}

export interface BlogPostNav {
	slug: string;
	title: string;
}

export interface AdjacentPosts {
	previous: BlogPostNav | null;
	next: BlogPostNav | null;
}

export function getAdjacentPosts(slug: string): AdjacentPosts {
	const index = allPosts.findIndex((post) => post.slug === slug);
	if (index === -1) return { previous: null, next: null };

	const older = allPosts[index + 1];
	const newer = allPosts[index - 1];

	return {
		previous: older ? { slug: older.slug, title: older.title } : null,
		next: newer ? { slug: newer.slug, title: newer.title } : null
	};
}

export function getAllTags(): string[] {
	const tags = new Set<string>();
	for (const post of allPosts) {
		for (const tag of post.tags) tags.add(tag);
	}
	return Array.from(tags).sort();
}
