import { getSessionUser } from "@/lib/auth";
import { normalizeSupportedLocale } from "@/lib/i18n-config";
import { plainTextToHtml } from "@/lib/mail-html";
import { translateMailboxMessageForEmail } from "@/lib/mail-message-translation";
import { getMailboxMessageBodyViewByEmail } from "@/lib/official-mail";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const DOCUMENT_HEADERS = {
  "Cache-Control": "private, no-store, max-age=0",
  "Content-Security-Policy": [
    "default-src 'none'",
    "base-uri 'none'",
    "connect-src 'none'",
    "font-src https: data:",
    "form-action 'none'",
    "frame-src 'none'",
    "img-src 'self' https: data:",
    "media-src https: data:",
    "object-src 'none'",
    "script-src 'none'",
    "style-src 'unsafe-inline' https:",
    "sandbox allow-same-origin allow-popups allow-popups-to-escape-sandbox",
  ].join("; "),
  "Content-Type": "text/html; charset=utf-8",
  "Referrer-Policy": "no-referrer",
  "X-Content-Type-Options": "nosniff",
};

function documentHtml(bodyHtml: string, lang: string, scrollable: boolean) {
  return [
    "<!doctype html>",
    `<html lang="${lang}">`,
    "<head>",
    '<meta charset="utf-8">',
    '<meta name="viewport" content="width=device-width, initial-scale=1">',
    scrollable ? "<style>html,body{min-height:100%;}</style>" : "<style>html,body{overflow:hidden!important;}</style>",
    "</head>",
    `<body>${bodyHtml}</body>`,
    "</html>",
  ].join("");
}

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

  if (!user) {
    return new Response("로그인이 필요합니다.", { status: 401, headers: DOCUMENT_HEADERS });
  }

  const { searchParams } = new URL(request.url);
  const messageId = Number(searchParams.get("message"));
  const targetLocale = normalizeSupportedLocale(searchParams.get("locale"));
  const translated = searchParams.get("translated") === "1";
  const scrollable = searchParams.get("view") === "popup";

  if (!Number.isInteger(messageId) || messageId <= 0) {
    return new Response("메일을 찾지 못했습니다.", { status: 404, headers: DOCUMENT_HEADERS });
  }

  const message = await getMailboxMessageBodyViewByEmail(user.email, messageId);
  if (!message) {
    return new Response("메일을 찾지 못했습니다.", { status: 404, headers: DOCUMENT_HEADERS });
  }

  let bodyHtml = message.bodyHtmlDisplay?.trim() || plainTextToHtml(message.bodyText);
  let lang = "ko";

  if (translated && targetLocale && message.direction === "inbound") {
    const translation = await translateMailboxMessageForEmail({
      email: user.email,
      messageId,
      targetLocale,
    });
    if (translation.status === "translated") {
      bodyHtml = translation.bodyHtml?.trim() || plainTextToHtml(translation.bodyText);
      lang = targetLocale;
    }
  }

  return new Response(documentHtml(bodyHtml, lang, scrollable), { headers: DOCUMENT_HEADERS });
}
