import { NextResponse } from "next/server";

import { requireApiAccess } from "../../../lib/api/auth";
import { caseListFiltersSchema } from "../../../lib/cases/validation";
import { getRepositoryFromRuntime } from "../../../lib/db/repository";

export async function GET(request: Request) {
  const access = requireApiAccess(request);
  if (!access.ok) {
    return access.response;
  }

  const url = new URL(request.url);
  const filters = caseListFiltersSchema.parse(
    Object.fromEntries(url.searchParams.entries()),
  );
  const repository = getRepositoryFromRuntime();

  return NextResponse.json({
    cases: await repository.listOptimizationCases(filters),
  });
}
