import type {APIRoute, GetStaticPaths} from 'astro';
import {loadScore} from '../../load-score.ts';
import {readdir} from 'fs/promises';

export const GET: APIRoute = async ({ params }) => {
	let data: string;
	try {
		data = await loadScore(params.id as string);
	} catch (err) {
		console.error(err);
		return new Response(null, { status: 500 });
	}

	return new Response(
		data,
		{
			headers: {
				'Content-Type': 'image/svg+xml',
			},
			status: 200,
		}
	);
};

export const getStaticPaths: GetStaticPaths = async () => {
	const files = await readdir('public/scores');
	return files
		.filter((f) => f.endsWith('.musicxml'))
		.map((f) => ({
			params: {
				id: f.replace(/\.musicxml/g, ''),
			},
		}));
};
