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 { serializeQuoteSummary } from "@/modules/quote/quote-serializer";

function parsePagination(searchParams: URLSearchParams): {
  page: number;
  size: number;
} | null {
  const pageRaw = searchParams.get("page");
  const sizeRaw = searchParams.get("size");

  if (!pageRaw || !sizeRaw) {
    return null;
  }

  const page = Number(pageRaw);
  const size = Number(sizeRaw);

  if (
    !Number.isInteger(page) ||
    !Number.isInteger(size) ||
    page < 1 ||
    size < 1 ||
    size > 100
  ) {
    return null;
  }

  return { page, size };
}

export async function GET(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 pagination = parsePagination(new URL(request.url).searchParams);
  if (!pagination) {
    return fail("VALIDATION_FAILED", "请提供有效的 page 和 size 参数", 400);
  }

  const { page, size } = pagination;
  const where = { customerId: auth.customerId, isDeleted: false };

  const [total, records] = await Promise.all([
    prisma.quoteRecord.count({ where }),
    prisma.quoteRecord.findMany({
      where,
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * size,
      take: size,
    }),
  ]);

  return ok({
    list: records.map(serializeQuoteSummary),
    total,
    page,
    size,
  });
}
