import { notFound } from "next/navigation";
import { requireSessionUser } from "@/lib/auth";
import { getMailboxMessageBodyViewByEmail } from "@/lib/official-mail";

type MailMessageBodyPageProps = {
  searchParams?: Promise<Record<string, string | string[] | undefined>>;
};

function pickParam(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function buildMailboxBodyDocument(html: string) {
  const normalized = html.trim();

  if (!normalized) {
    return "";
  }

  if (/<(?:!doctype|html|head|body)\b/i.test(normalized)) {
    return normalized;
  }

  return [
    "<!doctype html>",
    '<html lang="ko">',
    "<head>",
    '<meta charset="utf-8">',
    '<meta name="viewport" content="width=device-width, initial-scale=1">',
    '<base target="_blank">',
    "</head>",
    `<body>${normalized}</body>`,
    "</html>",
  ].join("");
}

export default async function MailMessageBodyPage({
  searchParams,
}: MailMessageBodyPageProps) {
  const user = await requireSessionUser();
  const params = searchParams ? await searchParams : {};
  const messageId = Number(pickParam(params.message));

  if (!Number.isInteger(messageId) || messageId <= 0) {
    notFound();
  }

  const message = await getMailboxMessageBodyViewByEmail(user.email, messageId);

  if (!message) {
    notFound();
  }

  const html = message.bodyHtmlDisplay?.trim() ?? "";

  return (
    <main className="min-h-screen bg-white">
      {html ? (
        <iframe
          title={message.subject.trim() || "메일 본문"}
          srcDoc={buildMailboxBodyDocument(html)}
          sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin"
          referrerPolicy="no-referrer"
          className="block h-screen w-full border-0 bg-white"
        />
      ) : (
        <pre className="min-h-screen whitespace-pre-wrap break-words bg-white p-6 text-[15px] leading-7 text-[#1f2c45]">
          {message.bodyText}
        </pre>
      )}
    </main>
  );
}
