import { sendSignupRecoveryEmailVerification } from "@/lib/official-mail";

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

type SendSignupRecoveryEmailRequestBody = {
  challengeId?: number | null;
  recoveryEmail?: string;
};

function mapSendError(error: unknown) {
  if (!(error instanceof Error)) {
    return {
      error: "system",
      message: "인증번호 전송 중 오류가 발생했습니다.",
      status: 500,
    };
  }

  if (error.message === "recovery-email-required") {
    return {
      error: "recovery-email-required",
      message: "보조 이메일을 입력해주세요.",
      status: 400,
    };
  }

  if (error.message === "recovery-email-invalid") {
    return {
      error: "recovery-email-invalid",
      message: "보조 이메일 형식이 올바르지 않습니다.",
      status: 400,
    };
  }

  if (error.message.startsWith("recovery-email-resend-cooldown:")) {
    const secondsRemaining = Number(error.message.split(":")[1] ?? "0");

    return {
      error: "recovery-email-resend-cooldown",
      message: `${Math.max(1, secondsRemaining)}초 뒤에 재발송 가능합니다.`,
      secondsRemaining: Math.max(1, secondsRemaining),
      status: 429,
    };
  }

  return {
    error: "system",
    message: "인증번호 전송 중 오류가 발생했습니다.",
    status: 500,
  };
}

export async function POST(request: Request) {
  let body: SendSignupRecoveryEmailRequestBody | null = null;

  try {
    body = await request.json();
  } catch {
    return Response.json(
      {
        error: "invalid-json",
        message: "요청 형식이 올바르지 않습니다.",
      },
      { status: 400 },
    );
  }

  try {
    const result = await sendSignupRecoveryEmailVerification({
      challengeId: body?.challengeId ?? null,
      recoveryEmail: body?.recoveryEmail ?? "",
    });

    return Response.json(result);
  } catch (error) {
    const mapped = mapSendError(error);

    if (mapped.status >= 500) {
      console.error("Signup recovery email request failed", error);
    }

    return Response.json(mapped, { status: mapped.status });
  }
}
