import { access, readFile } from 'node:fs/promises';
import { constants } from 'node:fs';
import { PRIVATE_PHOTO_UPLOAD_DIR } from '$env/static/private';
import * as path from 'node:path';
import { error, type ServerLoad } from '@sveltejs/kit';

export const GET: ServerLoad = async ({ params }) => {
    const { filename } = params;

    const proposedFilePath = path.join(PRIVATE_PHOTO_UPLOAD_DIR, filename);

    const fileExists = await access(proposedFilePath, constants.F_OK)
        .then(() => true)
        .catch(() => false);

    if (!fileExists) {
        console.warn(`File with name ${filename} not found.`);
        return error(404, 'File not found');
    }

    const file = await readFile(proposedFilePath);
    const fileExt = path.extname(filename);
    const contentType = `image/${fileExt.replace('.', '')}`;

    return new Response(file, { headers: { 'Content-Type': contentType } });
};
