import { prisma } from "#lib/server/prisma.js";
import { APIRoute } from "astro";
import * as fs from "fs";
import { fileURLToPath } from "url";
import { PERSISTENT_DIR } from "#lib/server/constants.js";

export const GET: APIRoute = async (Astro) => {
	const { uid } = Astro.params;

	const image = await prisma.bild.findUnique({
		where: {
			uid,
		},
	});

	if (!image) {
		return new Response(null, {
			status: 404,
		});
	}

	const path = fileURLToPath(
		new URL(`${PERSISTENT_DIR}/images/${image.uid}.jpg`, import.meta.url)
	);

	if (!fs.existsSync(path)) {
		return new Response(null, {
			status: 404,
		});
	}

	const buffer = fs.readFileSync(path);

	return new Response(buffer, {
		status: 200,
		headers: {
			"Content-Type": "image/jpeg",
		},
	});
};
