import { error } from '@sveltejs/kit';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { getAvatarUploadDir } from '$lib/server/avatar';
import type { RequestHandler } from './$types';

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

export const GET: RequestHandler = async ({ params }) => {
	const file = params.file;
	if (!file || !/^\d+\.(jpg|jpeg|png|webp|gif)$/.test(file)) {
		throw error(404, 'Avatar tidak ditemukan');
	}

	const ext = file.split('.').pop()!.toLowerCase();
	const filePath = path.join(getAvatarUploadDir(), file);

	try {
		const data = await readFile(filePath);
		return new Response(data, {
			headers: {
				'Content-Type': MIME[ext] ?? 'application/octet-stream',
				'Cache-Control': 'private, max-age=3600'
			}
		});
	} catch {
		throw error(404, 'Avatar tidak ditemukan');
	}
};
