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 { recordSecurityEvent } from "@/modules/audit/service";
import { submitQuote } from "@/modules/quote/orchestrator";
import {
  SecurityValidationError,
  ValidationError,
} 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 submitQuote(body);
    return ok(result);
  } catch (error) {
    if (error instanceof SecurityValidationError) {
      void recordSecurityEvent(
        "SECURITY_VALIDATION_BLOCKED",
        auth.customerId,
        "POST /api/quotes",
        { message: error.message },
      );
      return fail("VALIDATION_FAILED", error.message, 400);
    }
    if (error instanceof ValidationError) {
      return fail("VALIDATION_FAILED", error.message, 400);
    }
    console.error("[POST /api/quotes] 异常:", error);
    return fail("INTERNAL_ERROR", "询价处理失败", 500);
  }
}
