import { parseServiceAuth } from "@/lib/api/auth-context";
import { prisma } from "@/lib/prisma";
import { serializeMarkupConfig } from "@/modules/pricing/markup-service";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";

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) {
  try {
    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 = { isDeleted: false };

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

  return ok({
    list: configs.map((c) => serializeMarkupConfig(c)),
    total,
    page,
    size,
  });
}
