import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { documents } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { readFile } from 'node:fs/promises';
import path from 'node:path';

const UPLOADS_BASE = path.join(process.cwd(), 'uploads');

export async function GET(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session) return new Response('Unauthorized', { status: 401 });

  const { id } = await params;

  const doc = await db.query.documents.findFirst({
    where: eq(documents.id, id),
  });
  if (!doc || !doc.filePath) return new Response('Not found', { status: 404 });

  const filePath = path.join(UPLOADS_BASE, doc.filePath);

  // Path traversal guard — critical security check
  if (!filePath.startsWith(UPLOADS_BASE)) {
    return new Response('Forbidden', { status: 403 });
  }

  try {
    const buffer = await readFile(filePath);
    return new Response(buffer, {
      headers: { 'Content-Type': 'application/pdf' },
    });
  } catch {
    return new Response('File not found', { status: 404 });
  }
}
