export const prerender = true;

import path from 'node:path';
import { config } from '$lib/site.config.js';
import fs from 'node:fs';
import dayjs from 'dayjs';
import { html } from 'satori-html';
import satori from 'satori';
import { Resvg } from '@resvg/resvg-js';
import Vips from 'wasm-vips';
import chalk from 'chalk';
const vips = await Vips();

export async function GET({ url }) {
	const params = url.pathname.split('/');
	const post = {
		title: path.parse(decodeURI(params[4])).name,
		date: params[3] === 'null' ? '' : dayjs.unix(decodeURI(params[3])).format('YYYY/MM/DD')
	};
	console.log(chalk.blue(`${dayjs().format('HH:mm:ss')} [og:image] generating ${post.title}`));
	const image = vips.Image.newFromBuffer(
		new Resvg(
			await satori(
				html(`
<div style="display: flex; height: 100%; width: 100%; font-weight: 700; background: white">
	<div style="left: 96px; top: 48px; font-size: 128px; position: absolute">
		${`> `}${config.title}
	</div>
	<div
		style="
			display: flex;
			flex-direction: column;
			position: absolute;
			left: 96px;
			bottom: 48px;
			width: 80%;
			color: black;
		"
	>
		<div style="font-size: 144px">${post.title}</div>
		<div style="display: flex; width: 100%; font-size: 96px; font-weight: 400">
			${post.date}
		</div>
	</div>
</div>
				`),
				{
					fonts: [
						{
							name: 'IBM Plex Sans',
							data: fs.readFileSync('./src/lib/font/IBMPlexSans-Regular.otf'),
							weight: 400,
							style: 'normal'
						},
						{
							name: 'IBM Plex Sans',
							data: fs.readFileSync('./src/lib/font/IBMPlexSans-Bold.otf'),
							weight: 700,
							style: 'normal'
						},
						{
							name: 'Noto Sans SC',
							data: fs.readFileSync('./src/lib/font/NotoSansSC-Regular.otf'),
							weight: 400,
							style: 'normal'
						},
						{
							name: 'Noto Sans SC',
							data: fs.readFileSync('./src/lib/font/NotoSansSC-Bold.otf'),
							weight: 700,
							style: 'normal'
						}
					],
					width: 2000,
					height: 1000
				}
			)
		)
			.render()
			.asPng()
	).webpsaveBuffer();
	return new Response(image);
}
