import { assertCustomerMatch, parseServiceAuth } from "@/lib/api/auth-context";
import { enforceRateLimits } from "@/lib/api/rate-limit";
import { requestSessionAddressConfirm } from "@/modules/address/session-confirm-queue";
import { sessionAddressConfirmSchema } from "@/modules/address/validation";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { RpaError } from "@/modules/rpa/errors";

export const maxDuration = 120;

/** 用户确认 MotherShip 地址后，在同驻留页锁定双地址（单次 RPA 会话续跑前置） */
export async function POST(request: Request) {
  let auth;
  try {
    auth = await parseServiceAuth(request);
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const rateLimited = await enforceRateLimits(request, auth.customerId);
  if (rateLimited) {
    return rateLimited;
  }

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return fail("VALIDATION_FAILED", "请求体格式无效", 400);
  }

  const parsed = sessionAddressConfirmSchema.safeParse(body);
  if (!parsed.success) {
    const message = parsed.error.issues[0]?.message ?? "参数无效";
    return fail("VALIDATION_FAILED", message, 400);
  }

  try {
    assertCustomerMatch(auth, parsed.data.customer_id);
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  try {
    await requestSessionAddressConfirm({
      sessionId: parsed.data.quote_session_id,
      pickup: parsed.data.pickup,
      delivery: parsed.data.delivery,
    });
    return ok({ confirmed: true });
  } catch (error) {
    if (error instanceof RpaError) {
      return fail(error.code, error.message, 503);
    }
    console.error("[mothership-candidates/confirm]", error);
    return fail(
      "INTERNAL_ERROR",
      error instanceof Error ? error.message : "地址确认失败",
      503,
    );
  }
}
