import { assertCustomerMatch, parseServiceAuth } from "@/lib/api/auth-context";
import { enforceRateLimits } from "@/lib/api/rate-limit";
import { resolveAxelMothershipSuggest } from "@/lib/axel/candidates";
import { mothershipSuggestBodySchema } from "@/modules/address/validation";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";

export const maxDuration = 60;

/** POST /api/addresses/mothership-suggest — 单 query 地址联想（登录后一级表单） */
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 = mothershipSuggestBodySchema.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 {
    const candidates = await resolveAxelMothershipSuggest(parsed.data.query);
    return ok({ candidates });
  } catch (error) {
    console.error("[mothership-suggest]", error);
    const message =
      error instanceof Error ? error.message : "地址联想服务异常";
    return fail("INTERNAL_ERROR", message, 503);
  }
}
