import type { APIRoute } from 'astro';
import { Session } from '@util/session.ts';
import { Permissions } from '@util/permissions.ts';
import fs from 'node:fs';
import path from 'node:path';
import { UPLOAD_PATH } from 'astro:env/server';

export const GET: APIRoute = async ({ params, cookies }) => {
  Session.actionSessionFromCookies(cookies, Permissions.Reports);

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

  const fileHash = params.fileHash as string;
  const filePath = path.join(UPLOAD_PATH, fileHash);

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

  const fileStat = fs.statSync(filePath);
  const fileStream = fs.createReadStream(filePath);

  return new Response(fileStream as any, {
    status: 200,
    headers: {
      'Content-Length': fileStat.size.toString()
    }
  });
};
