import { error } from '@sveltejs/kit';
import { readFile } from 'node:fs/promises';
import { imageRepository } from '$lib/server/db/repository';
import { getThumbnailPath } from '$lib/server/images/storage';
import type { RequestHandler } from './$types';

export const GET: RequestHandler = async ({ params }) => {
	const { id } = params;

	const image = imageRepository.getById(id);
	if (!image) {
		error(404, 'Image not found');
	}

	try {
		const path = getThumbnailPath(id);
		const buffer = await readFile(path);

		return new Response(buffer, {
			headers: {
				'Content-Type': 'image/jpeg',
				'Content-Length': buffer.length.toString(),
				'Cache-Control': 'public, max-age=31536000, immutable'
			}
		});
	} catch {
		error(404, 'Thumbnail not found');
	}
};
