import { parseServiceAuth } from "@/lib/api/auth-context";
import { prisma } from "@/lib/prisma";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { recordSecurityEvent } from "@/modules/audit/service";
import { serializeQuoteDetail } from "@/modules/quote/quote-serializer";

type RouteContext = {
  params: Promise<{ quote_id: string }>;
};

export async function GET(request: Request, context: RouteContext) {
  let auth;
  try {
    auth = await parseServiceAuth(request);
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const { quote_id: quoteId } = await context.params;

  const record = await prisma.quoteRecord.findFirst({
    where: { quoteId, isDeleted: false },
  });

  if (!record) {
    return fail("QUOTE_NOT_FOUND", "报价不存在", 404);
  }

  if (record.customerId !== auth.customerId) {
    void recordSecurityEvent(
      "FORBIDDEN_ACCESS",
      auth.customerId,
      quoteId,
      {
        attempted_quote_id: quoteId,
        owner_customer_id: record.customerId,
      },
    );
    return fail("FORBIDDEN", "无权访问该报价", 403);
  }

  return ok(serializeQuoteDetail(record));
}
