import { parseServiceAuth } from "@/lib/api/auth-context";
import { enforceRateLimits } from "@/lib/api/rate-limit";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import {
  hostPublicResolveCandidates,
  HostPublicError,
  HostQuoteWaitError,
} from "@/modules/host/public-orchestrator";
import { hostCandidatesBodySchema } from "@/modules/host/validation";
import { RpaError } from "@/modules/rpa/errors";

export const maxDuration = 300;

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 = hostCandidatesBodySchema.safeParse(body);
  if (!parsed.success) {
    const message = parsed.error.issues[0]?.message ?? "参数无效";
    return fail("VALIDATION_FAILED", message, 400);
  }

  try {
    const result = await hostPublicResolveCandidates(auth.customerId, parsed.data);
    return ok(result);
  } catch (error) {
    if (error instanceof HostPublicError) {
      return fail(error.code, error.message, 400);
    }
    if (error instanceof RpaError) {
      return fail(error.code, error.message, 503);
    }
    console.error("[host/quote/candidates]", error);
    return fail("INTERNAL_ERROR", "地址联想失败", 503);
  }
}
