import { error } from '@sveltejs/kit';
import fs from 'node:fs';
import path from 'node:path';
import type { RequestHandler } from './$types';

const IMAGE_BASE_DIRECTORY = '/workspace';

export const GET: RequestHandler = ({ params }) => {
  const imagePath = params.path;
  if (imagePath.includes('..')) {
    throw error(403, 'Forbidden');
  }
  const fullPath = path.join(IMAGE_BASE_DIRECTORY, imagePath);
  if (!fs.existsSync(fullPath)) {
    throw error(404, 'Not Found');
  }
  try {
    const fileBuffer = fs.readFileSync(fullPath);
    const fileExtension = path.extname(fullPath).toLowerCase();
    let mimeType = 'application/octet-stream';
    switch (fileExtension) {
      case '.png': mimeType = 'image/png'; break;
      case '.jpg': case '.jpeg': mimeType = 'image/jpeg'; break;
      case '.bmp': mimeType = 'image/bmp'; break;
      case '.gif': mimeType = 'image/gif'; break;
    }
    return new Response(fileBuffer, {
      headers: {
        'Content-Type': mimeType,
        'Content-Length': fileBuffer.length.toString(),
      },
    });
  } catch (e) {
    console.error(`Failed to read file: ${fullPath}`, e);
    throw error(500, 'Internal Server Error');
  }
};
