import { createMailboxMessage } from "@/lib/official-mail";
import { authenticateMailboxDeveloperApiKey } from "@/lib/mail-integrations";

const MAX_RECIPIENTS = 50;
const MAX_TEXT_LENGTH = 1_000_000;
const MAX_HTML_LENGTH = 2_000_000;

type SendMailRequest = {
  bcc?: unknown;
  cc?: unknown;
  html?: unknown;
  subject?: unknown;
  text?: unknown;
  to?: unknown;
};

function readBearerToken(request: Request) {
  const authorization = request.headers.get("authorization")?.trim() ?? "";
  const [scheme, token] = authorization.split(/\s+/, 2);

  if (scheme?.toLowerCase() !== "bearer" || !token) {
    return "";
  }

  return token.trim();
}

function normalizeAddressField(value: unknown) {
  if (Array.isArray(value)) {
    return value
      .filter((item): item is string => typeof item === "string")
      .map((item) => item.trim())
      .filter(Boolean)
      .join(", ");
  }

  return typeof value === "string" ? value.trim() : "";
}

function countRecipients(...fields: string[]) {
  return new Set(
    fields
      .flatMap((field) => field.split(/[\n,;]+/))
      .map((value) => value.trim().toLowerCase())
      .filter(Boolean),
  ).size;
}

function apiError(status: number, code: string, message: string, retryAfter?: number) {
  return Response.json(
    { error: { code, message, ...(retryAfter ? { retryAfter } : {}) }, ok: false },
    {
      headers: retryAfter ? { "Retry-After": String(retryAfter) } : undefined,
      status,
    },
  );
}

function mapSendError(error: unknown) {
  const message = error instanceof Error ? error.message : "";

  if (message === "invalid-recipient") {
    return apiError(400, "invalid_recipient", "받는 사람 이메일 주소를 확인해주세요.");
  }

  if (message === "compose-required") {
    return apiError(400, "required_fields", "받는 사람, 제목, 본문을 모두 입력해주세요.");
  }

  if (message === "compose-subject-too-long") {
    return apiError(400, "subject_too_long", "제목은 255자 이하로 입력해주세요.");
  }

  if (message === "free-send-limit-daily") {
    return apiError(429, "daily_limit", "무료 플랜의 오늘 발송 한도를 모두 사용했습니다.");
  }

  if (message.startsWith("send-cooldown-active:")) {
    const detail = message.slice("send-cooldown-active:".length).trim();
    const retryAfter = Number(detail.match(/(\d+)초/)?.[1] ?? 60);
    return apiError(429, "rate_limited", detail || "잠시 후 다시 시도해주세요.", retryAfter);
  }

  if (message === "mailbox-not-found" || message === "mailbox-auth-missing") {
    return apiError(409, "mailbox_not_ready", "메일함 연결 상태를 확인해주세요.");
  }

  console.error("[developer-mail-api] send failed", error);
  return apiError(503, "send_unavailable", "메일 전송을 준비하지 못했습니다. 잠시 후 다시 시도해주세요.");
}

export async function POST(request: Request) {
  const token = readBearerToken(request);

  if (!token) {
    return apiError(401, "missing_api_key", "Authorization 헤더에 Bearer API 키를 입력해주세요.");
  }

  let authenticated: Awaited<ReturnType<typeof authenticateMailboxDeveloperApiKey>>;

  try {
    authenticated = await authenticateMailboxDeveloperApiKey(token);
  } catch (error) {
    console.error("[developer-mail-api] authentication failed", error);
    return apiError(503, "authentication_unavailable", "API 키를 확인하지 못했습니다. 잠시 후 다시 시도해주세요.");
  }

  if (!authenticated) {
    return apiError(401, "invalid_api_key", "API 키가 올바르지 않거나 폐기되었습니다.");
  }

  if (!authenticated.growthPlanAvailable) {
    return apiError(403, "growth_plan_required", "발송 API는 성장 플랜부터 이용할 수 있습니다.");
  }

  let body: SendMailRequest;

  try {
    body = await request.json();
  } catch {
    return apiError(400, "invalid_json", "JSON 요청 본문을 확인해주세요.");
  }

  const to = normalizeAddressField(body.to);
  const cc = normalizeAddressField(body.cc);
  const bcc = normalizeAddressField(body.bcc);
  const subject = typeof body.subject === "string" ? body.subject.trim() : "";
  const text = typeof body.text === "string" ? body.text : "";
  const html = typeof body.html === "string" ? body.html : "";
  const recipientCount = countRecipients(to, cc, bcc);

  if (!to || !subject || (!text.trim() && !html.trim())) {
    return apiError(400, "required_fields", "to, subject와 text 또는 html을 입력해주세요.");
  }

  if (recipientCount > MAX_RECIPIENTS) {
    return apiError(400, "too_many_recipients", `한 요청에는 최대 ${MAX_RECIPIENTS}명까지 지정할 수 있습니다.`);
  }

  if (subject.length > 255 || text.length > MAX_TEXT_LENGTH || html.length > MAX_HTML_LENGTH) {
    return apiError(413, "content_too_large", "제목 또는 본문 길이가 허용 범위를 초과했습니다.");
  }

  try {
    const result = await createMailboxMessage(authenticated.mailboxEmail, {
      bcc,
      body: text,
      bodyHtml: html,
      cc,
      intent: "send",
      sendSource: "api",
      subject,
      to,
      waitForDelivery: false,
    });

    return Response.json(
      {
        data: {
          from: authenticated.mailboxEmail,
          messageId: result.messageId,
          recipientCount,
          status: "queued",
        },
        ok: true,
      },
      { status: 202 },
    );
  } catch (error) {
    return mapSendError(error);
  }
}
