import "server-only";

import { OverallScoreMethod } from "@prisma/client";
import { prisma } from "@/lib/prisma";

export type EffectiveScoringConfig = {
  key: string;
  lowScoreThreshold: number;
  overallScoreMethod: OverallScoreMethod;
  moduleWeights: Record<string, number>;
};

export const DEFAULT_SCORING_CONFIG: EffectiveScoringConfig = {
  key: "default",
  lowScoreThreshold: 70,
  overallScoreMethod: OverallScoreMethod.EQUAL_ALL_MODULES,
  moduleWeights: {},
};

function parseModuleWeights(value: unknown): Record<string, number> {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }

  const objectValue = value as Record<string, unknown>;
  const parsed: Record<string, number> = {};

  for (const [key, rawWeight] of Object.entries(objectValue)) {
    const numericWeight = typeof rawWeight === "number" ? rawWeight : Number.parseFloat(String(rawWeight));

    if (!Number.isNaN(numericWeight) && Number.isFinite(numericWeight) && numericWeight > 0) {
      parsed[key] = numericWeight;
    }
  }

  return parsed;
}

export async function getScoringConfig(): Promise<EffectiveScoringConfig> {
  try {
    const scoringConfig = await prisma.scoringConfig.findUnique({
      where: { key: DEFAULT_SCORING_CONFIG.key },
      select: {
        key: true,
        lowScoreThreshold: true,
        overallScoreMethod: true,
        moduleWeights: true,
      },
    });

    if (!scoringConfig) {
      const created = await prisma.scoringConfig.create({
        data: {
          key: DEFAULT_SCORING_CONFIG.key,
          lowScoreThreshold: DEFAULT_SCORING_CONFIG.lowScoreThreshold,
          overallScoreMethod: DEFAULT_SCORING_CONFIG.overallScoreMethod,
          moduleWeights: DEFAULT_SCORING_CONFIG.moduleWeights,
        },
        select: {
          key: true,
          lowScoreThreshold: true,
          overallScoreMethod: true,
          moduleWeights: true,
        },
      });

      return {
        key: created.key,
        lowScoreThreshold: created.lowScoreThreshold,
        overallScoreMethod: created.overallScoreMethod,
        moduleWeights: parseModuleWeights(created.moduleWeights),
      };
    }

    return {
      key: scoringConfig.key,
      lowScoreThreshold: scoringConfig.lowScoreThreshold,
      overallScoreMethod: scoringConfig.overallScoreMethod,
      moduleWeights: parseModuleWeights(scoringConfig.moduleWeights),
    };
  } catch {
    return DEFAULT_SCORING_CONFIG;
  }
}
