import { prisma } from "@/server/db";

const SUPPORT_TIME_ZONE = "Europe/Zurich";

export function supportHoursLabel() {
  return "Lundi - Vendredi : 08:30 - 18:30";
}

export function ticketResponseLabel() {
  return "Réponse sous 2 à 3 heures durant les horaires d'ouverture";
}

export function isWithinSupportHours(date = new Date()) {
  const parts = new Intl.DateTimeFormat("en-GB", {
    timeZone: SUPPORT_TIME_ZONE,
    weekday: "short",
    hour: "2-digit",
    minute: "2-digit",
    hour12: false
  }).formatToParts(date);
  const weekday = parts.find((part) => part.type === "weekday")?.value ?? "";
  const hour = Number(parts.find((part) => part.type === "hour")?.value ?? 0);
  const minute = Number(parts.find((part) => part.type === "minute")?.value ?? 0);
  const weekdayIndex = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(weekday);
  const minutes = hour * 60 + minute;

  return weekdayIndex >= 0 && weekdayIndex <= 4 && minutes >= 8 * 60 + 30 && minutes <= 18 * 60 + 30;
}

export async function getSupportAvailability() {
  const availability = await prisma.supportAvailability.findUnique({ where: { id: "default" } });
  const fallbackOnline = isWithinSupportHours();

  return {
    liveChatOnline: availability?.isLiveChatOnline ?? fallbackOnline,
    message: availability?.message ?? (fallbackOnline ? "Support en ligne" : "Support hors ligne"),
    supportHours: supportHoursLabel(),
    ticketResponseTime: ticketResponseLabel(),
    updatedAt: availability?.updatedAt ?? null
  };
}
