import { getSessionUser } from "@/lib/auth";
import { reviewMailBillingCancellationRequestById } from "@/lib/billing-cancellation";
import { isKavenixAdminEmail } from "@/lib/kavenix-admin";

type ReviewRequestPayload = {
  action?: "approve_full" | "approve_partial" | "reject";
  note?: string | null;
  refundAmount?: number | null;
};

function normalizeReviewErrorMessage(message: string) {
  if (message === "billing-cancellation-request-not-found") {
    return "청약철회 요청을 찾을 수 없습니다.";
  }

  if (message === "billing-cancellation-review-not-supported") {
    return "이 요청은 관리자 청약철회 검토 대상이 아닙니다.";
  }

  if (message === "billing-cancellation-request-not-pending") {
    return "이미 처리가 시작되었거나 종료된 요청입니다.";
  }

  if (message === "billing-cancellation-request-already-reviewed") {
    return "이미 검토가 끝난 청약철회 요청입니다.";
  }

  if (message === "billing-cancellation-partial-refund-amount-invalid") {
    return "부분 환불 금액을 올바르게 입력해 주세요.";
  }

  if (message === "billing-cancellation-partial-refund-amount-exceeds-remaining") {
    return "남은 환불 가능 금액을 초과할 수 없습니다.";
  }

  if (message === "billing-profile-inactive") {
    return "구독 복구에 필요한 결제수단 상태가 비활성이라 반려를 완료할 수 없습니다.";
  }

  return message;
}

export async function POST(
  request: Request,
  context: RouteContext<"/api/kavenix/cancellations/[requestId]/review">,
) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json(
      {
        error: "unauthorized",
        message: "로그인이 필요합니다.",
      },
      { status: 401 },
    );
  }

  if (!isKavenixAdminEmail(user.email)) {
    return Response.json(
      {
        error: "forbidden",
        message: "최고관리자만 청약철회 검토를 처리할 수 있습니다.",
      },
      { status: 403 },
    );
  }

  const { requestId } = await context.params;
  const numericRequestId = Number(requestId);

  if (!Number.isInteger(numericRequestId) || numericRequestId <= 0) {
    return Response.json(
      {
        error: "invalid-request-id",
        message: "유효한 청약철회 요청 ID가 아닙니다.",
      },
      { status: 400 },
    );
  }

  let payload: ReviewRequestPayload = {};

  try {
    payload = (await request.json()) as ReviewRequestPayload;
  } catch {
    payload = {};
  }

  if (
    payload.action !== "approve_full" &&
    payload.action !== "approve_partial" &&
    payload.action !== "reject"
  ) {
    return Response.json(
      {
        error: "invalid-action",
        message: "청약철회 검토 동작이 올바르지 않습니다.",
      },
      { status: 400 },
    );
  }

  try {
    const cancellation = await reviewMailBillingCancellationRequestById({
      action: payload.action,
      note: payload.note,
      refundAmount: payload.refundAmount,
      requestId: numericRequestId,
      reviewedByEmail: user.email,
    });

    return Response.json({
      cancellation,
      message: cancellation.message,
      ok: true,
    });
  } catch (error) {
    return Response.json(
      {
        error: "cancellation-review-failed",
        message:
          error instanceof Error
            ? normalizeReviewErrorMessage(error.message)
            : "청약철회 검토 처리에 실패했습니다.",
      },
      { status: 400 },
    );
  }
}
