import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { EVENT_CATEGORIES } from "@/lib/constants";
import { pushNotification } from "@/lib/notify-push";
import { formatDate } from "@/lib/utils";

/** Events: stats + upcoming/past lists. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const today = new Date(new Date().toISOString().slice(0, 10));

  const events = await prisma.eventItem.findMany({
    where: { institutionId: session.institutionId },
    orderBy: [{ startDate: "asc" }],
  });

  type EventRow = (typeof events)[number];
  const mapEvent = (e: EventRow) => ({
    id: e.id,
    title: e.title,
    titleBn: e.titleBn,
    description: e.description,
    venue: e.venue,
    category: e.category,
    startDate: e.startDate.toISOString().slice(0, 10),
    endDate: e.endDate ? e.endDate.toISOString().slice(0, 10) : null,
    isActive: e.isActive,
  });

  const upcoming = events.filter((e) => e.isActive && e.startDate >= today).map(mapEvent);
  const past = events.filter((e) => !e.isActive || e.startDate < today).map(mapEvent).reverse();

  const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
  return NextResponse.json({
    stats: {
      total: events.length,
      upcoming: upcoming.length,
      thisMonth: events.filter((e) => e.isActive && e.startDate >= today && e.startDate <= monthEnd).length,
      past: past.length,
    },
    upcoming,
    past,
  });
}

/** Create an event. */
export async function POST(req: Request) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  try {
    const body = await req.json();
    const title = String(body.title ?? "").trim();
    const startDate = String(body.startDate ?? "");
    if (!title || !/^\d{4}-\d{2}-\d{2}$/.test(startDate)) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const event = await prisma.eventItem.create({
      data: {
        institutionId: session.institutionId,
        title,
        titleBn: String(body.titleBn ?? "").trim() || null,
        description: String(body.description ?? "").trim() || null,
        venue: String(body.venue ?? "").trim() || null,
        category: EVENT_CATEGORIES.includes(body.category as never) ? body.category : "ACADEMIC",
        startDate: new Date(startDate),
        endDate: body.endDate ? new Date(String(body.endDate)) : null,
        isActive: true,
      },
    });

  // push notification to the chosen recipient groups (default: everyone)
  const groups: string[] = Array.isArray(body.notifyGroups)
    ? body.notifyGroups.map(String)
    : ["students", "parents", "teachers", "staff"];
  const details = [
    String(event.description ?? "").trim(),
    event.venue ? `Venue: ${event.venue}` : "",
    formatDate(event.startDate),
  ].filter(Boolean).join(" · ");
  await pushNotification({
    institutionId: session.institutionId,
    kind: "EVENT",
    title: event.title,
    body: details.slice(0, 300),
    link: null,
    audience: groups,
    refId: event.id,
    createdById: session.userId,
  });

    return NextResponse.json({ event });
  } catch {
    return NextResponse.json({ error: "Could not create event" }, { status: 500 });
  }
}
