import { assertCustomerMatch, 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 {
  FlockEnqueueError,
  submitFlockQuote,
} from "@/modules/flock/orchestrator";
import { ValidationError, QuoteIdConflictError } from "@/modules/quote/types";

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 bodyCustomerId =
    typeof body === "object" &&
    body !== null &&
    "customer_id" in body &&
    typeof (body as { customer_id: unknown }).customer_id === "string"
      ? (body as { customer_id: string }).customer_id
      : null;

  if (!bodyCustomerId) {
    return fail("VALIDATION_FAILED", "请填写客户标识", 400);
  }

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

  try {
    const result = await submitFlockQuote(body);
    return ok(result);
  } catch (error) {
    if (error instanceof ValidationError) {
      return fail("VALIDATION_FAILED", error.message, 400);
    }
    if (error instanceof QuoteIdConflictError) {
      return fail(error.code, error.message, 500);
    }
    if (error instanceof FlockEnqueueError) {
      return fail(error.code, error.message, 503);
    }
    console.error("[POST /api/flock/quotes] 异常:", error);
    return fail("INTERNAL_ERROR", "服务异常，请稍后重试", 500);
  }
}
