import { UserRole } from "@prisma/client";

import { requireRole } from "@/lib/auth-utils";
import { prisma } from "@/lib/prisma";
import { AdminCalendarManager } from "./admin-calendar-manager";

export const metadata = { title: "Event-Anmeldungen · Kita-Planer" };

export default async function AdminKalenderPage() {
  const session = await requireRole([UserRole.ADMIN, UserRole.KOORDINATOR]);
  const kitaId = session.user.kitaId;

  if (!kitaId) {
    return <div className="p-8">Kein Mandant zugeordnet.</div>;
  }

  const [termine, children] = await Promise.all([
    prisma.termin.findMany({
      where: { kitaId },
      select: {
        id: true,
        title: true,
        description: true,
        type: true,
        status: true,
        startDate: true,
        endDate: true,
        allDay: true,
        mitbringselListEnabled: true,
        requiresRsvp: true,
        rsvpDeadline: true,
        participantInfo: true,
        participations: {
          select: {
            childId: true,
            status: true,
          },
        },
      },
      orderBy: { startDate: "desc" },
    }),
    prisma.child.findMany({
      where: {
        kitaId,
        active: true,
      },
      select: {
        id: true,
        firstName: true,
        lastName: true,
        family: {
          select: {
            name: true,
          },
        },
      },
      orderBy: [
        { family: { name: "asc" } },
        { lastName: "asc" },
        { firstName: "asc" },
      ],
    }),
  ]);

  return (
    <AdminCalendarManager
      termine={termine.map((termin) => ({
        ...termin,
        startDate: termin.startDate.toISOString(),
        endDate: termin.endDate.toISOString(),
        rsvpDeadline: termin.rsvpDeadline?.toISOString() ?? null,
      }))}
      childRows={children.map((child) => ({
        id: child.id,
        name: `${child.firstName} ${child.lastName}`,
        familyName: child.family.name,
      }))}
    />
  );
}
