import { NextResponse } from "next/server";
import { OverallScoreMethod } from "@prisma/client";
import { requireAdminApiUser } from "@/lib/auth/admin";
import { DEFAULT_SCORING_CONFIG } from "@/lib/scoring-config";
import { prisma } from "@/lib/prisma";
import { buildAppUrl } from "@/lib/http/url";

function redirectTo(request: Request, status: string) {
  return NextResponse.redirect(buildAppUrl(request, "/admin", { status }));
}

function asString(formData: FormData, key: string) {
  const value = formData.get(key);
  return typeof value === "string" ? value.trim() : "";
}

export async function POST(request: Request) {
  const adminUser = await requireAdminApiUser();

  if (!adminUser) {
    return redirectTo(request, "admin_error");
  }

  const formData = await request.formData();

  const thresholdCandidate = Number.parseInt(asString(formData, "lowScoreThreshold") || "70", 10);
  const lowScoreThreshold = Number.isNaN(thresholdCandidate) ? 70 : Math.min(100, Math.max(0, thresholdCandidate));

  const methodCandidate = asString(formData, "overallScoreMethod");
  const allowedMethods = Object.values(OverallScoreMethod);
  const overallScoreMethod = allowedMethods.includes(methodCandidate as OverallScoreMethod)
    ? (methodCandidate as OverallScoreMethod)
    : OverallScoreMethod.EQUAL_ALL_MODULES;

  const moduleWeights: Record<string, number> = {};

  for (const [key, rawValue] of formData.entries()) {
    if (!key.startsWith("weight:")) {
      continue;
    }

    const moduleKey = key.replace("weight:", "").trim();
    const numericValue = Number.parseFloat(typeof rawValue === "string" ? rawValue : String(rawValue));

    if (moduleKey && !Number.isNaN(numericValue) && Number.isFinite(numericValue) && numericValue > 0) {
      moduleWeights[moduleKey] = numericValue;
    }
  }

  try {
    await prisma.scoringConfig.upsert({
      where: {
        key: DEFAULT_SCORING_CONFIG.key,
      },
      update: {
        lowScoreThreshold,
        overallScoreMethod,
        moduleWeights,
      },
      create: {
        key: DEFAULT_SCORING_CONFIG.key,
        lowScoreThreshold,
        overallScoreMethod,
        moduleWeights,
      },
    });

    return redirectTo(request, "scoring_updated");
  } catch {
    return redirectTo(request, "admin_error");
  }
}
