import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { EVENT_CATEGORIES } from "@/lib/constants";

type Params = { params: Promise<{ id: string }> };

/** Update an event. */
export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;
  try {
    const body = await req.json();
    const event = await prisma.eventItem.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!event) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const title = String(body.title ?? event.title).trim();
    const startDate = body.startDate ? String(body.startDate) : event.startDate.toISOString().slice(0, 10);
    if (!title || !/^\d{4}-\d{2}-\d{2}$/.test(startDate)) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }
    if (body.endDate !== undefined && body.endDate && String(body.endDate) < startDate) {
      return NextResponse.json({ error: "End date cannot be before start date" }, { status: 400 });
    }

    await prisma.eventItem.update({
      where: { id: event.id },
      data: {
        title,
        titleBn: body.titleBn !== undefined ? String(body.titleBn).trim() || null : event.titleBn,
        description: body.description !== undefined ? String(body.description).trim() || null : event.description,
        venue: body.venue !== undefined ? String(body.venue).trim() || null : event.venue,
        category: EVENT_CATEGORIES.includes(body.category as never) ? body.category : event.category,
        startDate: new Date(startDate),
        endDate:
          body.endDate !== undefined ? (body.endDate ? new Date(String(body.endDate)) : null) : event.endDate,
        isActive: typeof body.isActive === "boolean" ? body.isActive : event.isActive,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update event" }, { status: 500 });
  }
}

/** Delete an event. */
export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;
  const event = await prisma.eventItem.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!event) return NextResponse.json({ error: "Not found" }, { status: 404 });
  await prisma.eventItem.delete({ where: { id: event.id } });
  return NextResponse.json({ success: true });
}
