import { parseAdminAuth } from "@/lib/api/admin-auth-context";
import { fail, ok } from "@/lib/response";
import { AuthError } from "@/modules/auth/errors";
import { listAdminMarkupConfigs } from "@/modules/pricing/markup-service";

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 {
    parseAdminAuth(request);
  } catch (error) {
    if (error instanceof AuthError) {
      return fail(error.code, error.message, error.httpStatus);
    }
    throw error;
  }

  const url = new URL(request.url);
  const pagination = parsePagination(url.searchParams);
  if (!pagination) {
    return fail("VALIDATION_FAILED", "请提供有效的 page 和 size 参数", 400);
  }

  const keyword = url.searchParams.get("keyword") ?? undefined;
  const data = await listAdminMarkupConfigs({
    page: pagination.page,
    size: pagination.size,
    keyword,
  });

  return ok(data);
}
