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

function buildContentDisposition(filename: string, inline: boolean) {
  const safeAscii = filename.replace(/[^\x20-\x7E]+/g, "_").replace(/["\\]/g, "_") || "attachment";
  const encoded = encodeURIComponent(filename);
  const dispositionType = inline ? "inline" : "attachment";

  return `${dispositionType}; filename="${safeAscii}"; filename*=UTF-8''${encoded}`;
}

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

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

  const { searchParams } = new URL(request.url);
  const messageId = Number(searchParams.get("message"));
  const attachmentIndex = Number(searchParams.get("index"));
  const mode = searchParams.get("mode") === "inline" ? "inline" : "download";

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

  const attachment = await getMailboxAttachmentByEmail(user.email, messageId, attachmentIndex);

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

  const inline = mode === "inline" && attachment.isPreviewable;

  return new Response(new Uint8Array(attachment.content), {
    headers: {
      "Cache-Control": "private, max-age=60",
      "Content-Disposition": buildContentDisposition(attachment.filename, inline),
      "Content-Length": String(attachment.content.length),
      "Content-Type": attachment.contentType || "application/octet-stream",
      "X-Content-Type-Options": "nosniff",
    },
  });
}
