import { getSessionUser } from "@/lib/auth";
import { getMailboxMessageRawSourceByEmail } from "@/lib/official-mail";

export async function GET(request: Request) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json({ error: "unauthorized" }, { status: 401 });
  }

  const messageId = Number(new URL(request.url).searchParams.get("message"));

  if (!Number.isInteger(messageId) || messageId <= 0) {
    return Response.json({ error: "invalid-params" }, { status: 400 });
  }

  const rawSource = await getMailboxMessageRawSourceByEmail(user.email, messageId);

  if (!rawSource) {
    return Response.json({ error: "message-source-not-found" }, { status: 404 });
  }

  return new Response(rawSource, {
    headers: {
      "Cache-Control": "private, no-store",
      "Content-Type": "text/plain; charset=utf-8",
      "X-Content-Type-Options": "nosniff",
    },
  });
}
