import "server-only";
import { prisma } from "@/lib/prisma";
import { getAbsenceTypes } from "@/lib/settings";

export type CalEventKind = "absence" | "task" | "meeting";

export type CalEvent = {
  id: string;
  kind: CalEventKind;
  title: string;
  color: string;
  startDate: string; // YYYY-MM-DD
  endDate: string; // YYYY-MM-DD
  time: string | null; // HH:MM (Meetings)
  href: string | null;
};

const KIND_META: Record<CalEventKind, { label: string; color: string }> = {
  absence: { label: "Abwesenheit", color: "#c8bcff" },
  task: { label: "Aufgabe", color: "#ffc36b" },
  meeting: { label: "Meeting", color: "#9ed7ff" },
};

function isoDay(d: Date): string {
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

/**
 * Sammelt alle für den Nutzer relevanten Ereignisse eines Monats:
 * genehmigte Abwesenheiten, Kanban-Deadlines (zugewiesen) und Meetings.
 */
export async function getCalendarMonth(userId: string, year: number, month: number): Promise<CalEvent[]> {
  const from = new Date(year, month, 1);
  const to = new Date(year, month + 1, 1);
  const events: CalEvent[] = [];

  const [absTypes, absences, tasks, meetings] = await Promise.all([
    getAbsenceTypes(),
    prisma.absenceRequest.findMany({
      where: { userId, status: "APPROVED", startDate: { lt: to }, endDate: { gte: from } },
      select: { id: true, type: true, startDate: true, endDate: true, reason: true },
    }),
    prisma.task.findMany({
      where: { archivedAt: null, deadline: { gte: from, lt: to }, assignees: { some: { userId } } },
      select: { id: true, title: true, deadline: true, priority: true },
    }),
    prisma.meeting.findMany({
      where: { startAt: { gte: from, lt: to }, participants: { some: { userId } } },
      select: { id: true, title: true, startAt: true, endAt: true },
    }),
  ]);

  const typeLabel = (k: string) => absTypes.find((t) => t.key === k)?.label ?? k;

  for (const a of absences) {
    events.push({
      id: `abs-${a.id}`,
      kind: "absence",
      // Abwesenheiten einheitlich in einer eigenen (violetten) Farbe, klar
      // unterscheidbar von Aufgaben (amber) und Meetings (blau).
      title: typeLabel(a.type),
      color: KIND_META.absence.color,
      startDate: isoDay(a.startDate),
      endDate: isoDay(a.endDate),
      time: null,
      href: "/absences",
    });
  }
  for (const t of tasks) {
    events.push({
      id: `task-${t.id}`,
      kind: "task",
      title: t.title,
      color: KIND_META.task.color,
      startDate: isoDay(t.deadline!),
      endDate: isoDay(t.deadline!),
      time: null,
      href: "/kanban",
    });
  }
  for (const m of meetings) {
    events.push({
      id: `mtg-${m.id}`,
      kind: "meeting",
      title: m.title,
      color: KIND_META.meeting.color,
      startDate: isoDay(m.startAt),
      endDate: isoDay(m.endAt),
      time: m.startAt.toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" }),
      href: "/meetings",
    });
  }

  return events;
}
