import { db } from "@/lib/db";
import { riskAssessmentHazards, nonConformances } from "@/lib/db/schema";
import { getRiskGrade } from "@/lib/constants";
import { DashboardCharts } from "./charts";

export async function DashboardChartsLoader() {
  let riskDistribution = [
    { name: "저위험", value: 0, color: "#22c55e" },
    { name: "보통", value: 0, color: "#eab308" },
    { name: "고위험", value: 0, color: "#f97316" },
    { name: "매우위험", value: 0, color: "#ef4444" },
  ];

  let ncrByStatus = [
    { name: "미조치", value: 0, color: "#ef4444" },
    { name: "시정조치", value: 0, color: "#f97316" },
    { name: "확인 중", value: 0, color: "#eab308" },
    { name: "종결", value: 0, color: "#22c55e" },
  ];

  try {
    // Risk distribution
    const hazards = await db
      .select({ riskLevel: riskAssessmentHazards.riskLevel })
      .from(riskAssessmentHazards);

    for (const h of hazards) {
      const grade = getRiskGrade(h.riskLevel);
      const idx = riskDistribution.findIndex(
        (d) =>
          d.name ===
          { low: "저위험", medium: "보통", high: "고위험", critical: "매우위험" }[
            grade.grade
          ]
      );
      if (idx >= 0) riskDistribution[idx].value++;
    }

    // NCR distribution
    const ncrs = await db
      .select({ status: nonConformances.status })
      .from(nonConformances);

    const ncrStatusMap: Record<string, number> = {
      open: 0,
      corrective_action: 1,
      verification: 2,
      closed: 3,
    };
    for (const n of ncrs) {
      const idx = ncrStatusMap[n.status];
      if (idx !== undefined) ncrByStatus[idx].value++;
    }
  } catch {
    // DB not connected yet
  }

  return (
    <DashboardCharts
      riskDistribution={riskDistribution}
      ncrByStatus={ncrByStatus}
    />
  );
}
