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

type MessageTranslationPayload = {
  messageId?: number | string;
  targetLocale?: string;
};

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

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

  const payload = (await request.json().catch(() => null)) as MessageTranslationPayload | null;
  const messageId = Number(payload?.messageId);
  const targetLocale = normalizeSupportedLocale(payload?.targetLocale);

  if (!Number.isInteger(messageId) || messageId <= 0 || !targetLocale) {
    return Response.json({ error: "invalid-payload", ok: false }, { status: 400 });
  }

  try {
    const translation = await translateMailboxMessageForEmail({
      email: user.email,
      messageId,
      targetLocale,
    });

    return Response.json(
      { ok: true, translation },
      {
        headers: {
          "Cache-Control": "private, no-store",
        },
      },
    );
  } catch (error) {
    const detail = error instanceof Error ? error.message : "mail-translation-failed";
    const status = detail === "mail-translation-message-not-found" ? 404 : 502;

    console.warn(
      `[mail-translation] failed user=${user.email} messageId=${messageId} target=${targetLocale} error=${detail}`,
    );

    return Response.json(
      {
        error: detail,
        ok: false,
      },
      {
        headers: {
          "Cache-Control": "private, no-store",
        },
        status,
      },
    );
  }
}
