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

const MIME_TYPES: Record<string, string> = {
	jpg: 'image/jpeg',
	jpeg: 'image/jpeg',
	png: 'image/png',
	gif: 'image/gif',
	webp: 'image/webp',
	heic: 'image/heic',
	heif: 'image/heif'
};

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

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

	try {
		const path = getOriginalPath(id, image.ext);
		const buffer = await readFile(path);
		const mimeType = MIME_TYPES[image.ext.toLowerCase()] || 'application/octet-stream';

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