import { NextResponse } from "next/server";

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

interface RouteContext {
  params: Promise<{ caseId: string }>;
}

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

  const { caseId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const detail = await repository.getOptimizationCaseDetail(caseId);
  if (!detail) {
    return NextResponse.json({ error: "Case not found" }, { status: 404 });
  }

  return NextResponse.json(detail);
}

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

  const { caseId } = await context.params;
  const repository = getRepositoryFromRuntime();
  const changes = caseMetadataPatchSchema.parse(await request.json());
  const optimizationCase = await repository.updateOptimizationCaseMetadata(
    caseId,
    changes,
  );
  if (!optimizationCase) {
    return NextResponse.json({ error: "Case not found" }, { status: 404 });
  }

  return NextResponse.json({ case: optimizationCase });
}
