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 {
  hostPublicSubmitAndWait,
  HostPublicError,
  HostQuoteWaitError,
} from "@/modules/host/public-orchestrator";
import { hostSubmitBodySchema } from "@/modules/host/validation";
import { ValidationError } from "@/modules/quote/types";

/** RPA 实时查价 + 内部轮询，与 QUOTE_TIMEOUT_MS 对齐 */
export const maxDuration = 420;

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

  try {
    const detail = await hostPublicSubmitAndWait(parsed.data);
    return ok(detail);
  } catch (error) {
    if (error instanceof HostPublicError) {
      const status = error.code === "SESSION_EXPIRED" ? 404 : 400;
      return fail(error.code, error.message, status);
    }
    if (error instanceof HostQuoteWaitError) {
      if (error.code === "QUOTE_TIMEOUT") {
        return fail(error.code, error.message, 504);
      }
      if (error.detail) {
        return ok(error.detail);
      }
      return fail(error.code, error.message, 422);
    }
    if (error instanceof ValidationError) {
      return fail("VALIDATION_FAILED", error.message, 400);
    }
    console.error("[host/quote/submit]", error);
    return fail("INTERNAL_ERROR", "询价处理失败", 500);
  }
}
