import { openLargeComposeAttachmentByToken } from "@/lib/mail-compose-uploads";
import { getMailAbsoluteUrl } from "@/lib/mail-urls";

export const runtime = "nodejs";

export async function GET(
  request: Request,
  context: { params: Promise<{ token: string }> },
) {
  const { token } = await context.params;
  const attachment = await openLargeComposeAttachmentByToken(token);
  if (!attachment) {
    const isBrowserNavigation = request.headers.get("sec-fetch-mode") === "navigate" ||
      request.headers.get("accept")?.includes("text/html");
    if (isBrowserNavigation) {
      return Response.redirect(getMailAbsoluteUrl("/attachment-expired"), 303);
    }
    return Response.json(
      { error: "attachment-expired-or-unavailable", message: "첨부파일이 만료되었습니다." },
      { status: 410, headers: { "Cache-Control": "no-store" } },
    );
  }
  const safeAscii = attachment.filename.replace(/[^\x20-\x7E]+/g, "_").replace(/["\\]/g, "_") || "attachment";
  return new Response(attachment.body, {
    headers: {
      "Cache-Control": "no-store",
      "Content-Disposition": `attachment; filename="${safeAscii}"; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
      ...(attachment.contentLength !== null
        ? { "Content-Length": String(attachment.contentLength) }
        : {}),
      "Content-Type": attachment.contentType,
      "X-Content-Type-Options": "nosniff",
    },
  });
}
