import { prisma } from "../config/prisma.js";

export interface PriorityInfo {
  priorityScore: number;
  status: "expired" | "critical" | "high" | "medium" | "low";
  label: string;
  color: string;
  daysRemaining: number;
}

export const PRIORITY_COLORS: Record<string, string> = {
  expired: "#dc2626",
  critical: "#ef4444",
  high: "#f97316",
  medium: "#eab308",
  low: "#22c55e",
};

export const PRIORITY_LABELS: Record<string, string> = {
  expired: "منتهي",
  critical: "حرجة",
  high: "عالية",
  medium: "متوسطة",
  low: "منخفضة",
};

async function getThresholds() {
  const settings = await prisma.setting.findMany({
    where: { key: { in: ["priority_critical_days", "priority_high_days", "priority_medium_days"] } },
  });
  const get = (k: string, d: number) => Number(settings.find((s) => s.key === k)?.value ?? d);
  return {
    critical: get("priority_critical_days", 7),
    high: get("priority_high_days", 30),
    medium: get("priority_medium_days", 60),
  };
}

export interface ExpirySummary {
  daysRemaining: number;
  status: "expired" | "critical" | "high" | "medium" | "low";
  label: string;
  color: string;
}

export function summarisePriority(priority: PriorityInfo): ExpirySummary {
  return {
    daysRemaining: priority.daysRemaining,
    status: priority.status,
    label: priority.label,
    color: priority.color,
  };
}

export function computePriority(
  expiryDate: Date | string,
  thresholds: { critical: number; high: number; medium: number }
): PriorityInfo {
  const expiry = new Date(expiryDate);
  const now = new Date();
  const daysRemaining = Math.floor((expiry.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

  if (daysRemaining < 0) {
    return { priorityScore: 100, status: "expired", label: PRIORITY_LABELS.expired, color: PRIORITY_COLORS.expired, daysRemaining };
  }
  if (daysRemaining <= thresholds.critical) {
    return { priorityScore: 80, status: "critical", label: PRIORITY_LABELS.critical, color: PRIORITY_COLORS.critical, daysRemaining };
  }
  if (daysRemaining <= thresholds.high) {
    return { priorityScore: 60, status: "high", label: PRIORITY_LABELS.high, color: PRIORITY_COLORS.high, daysRemaining };
  }
  if (daysRemaining <= thresholds.medium) {
    return { priorityScore: 40, status: "medium", label: PRIORITY_LABELS.medium, color: PRIORITY_COLORS.medium, daysRemaining };
  }
  return { priorityScore: 20, status: "low", label: PRIORITY_LABELS.low, color: PRIORITY_COLORS.low, daysRemaining };
}

export async function computePriorityForDate(expiryDate: Date | string): Promise<PriorityInfo> {
  const thresholds = await getThresholds();
  return computePriority(expiryDate, thresholds);
}
