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

/** Committees with their members. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const committees = await prisma.committee.findMany({
    where: { institutionId: session.institutionId },
    orderBy: [{ isActive: "desc" }, { id: "asc" }],
    include: {
      members: {
        orderBy: [{ role: "asc" }, { id: "asc" }],
        include: { staff: { select: { name: true, employeeCode: true, designation: true } } },
      },
    },
  });

  const totalMembers = committees.reduce((sum, c) => sum + c.members.length, 0);
  return NextResponse.json({
    stats: {
      committees: committees.length,
      active: committees.filter((c) => c.isActive).length,
      members: totalMembers,
    },
    committees: committees.map((c) => ({
      id: c.id,
      name: c.name,
      nameBn: c.nameBn,
      description: c.description,
      formedDate: c.formedDate ? c.formedDate.toISOString().slice(0, 10) : null,
      isActive: c.isActive,
      members: c.members.map((m) => ({
        id: m.id,
        name: m.staff?.name ?? m.memberName ?? "—",
        ref: m.staff ? m.staff.employeeCode : m.memberDesignation,
        isStaff: !!m.staffId,
        role: m.role,
      })),
    })),
  });
}

/** Create a committee. */
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 name = String(body.name ?? "").trim();
    if (!name) return NextResponse.json({ error: "Missing fields" }, { status: 400 });

    const committee = await prisma.committee.create({
      data: {
        institutionId: session.institutionId,
        name,
        nameBn: String(body.nameBn ?? "").trim() || null,
        description: String(body.description ?? "").trim() || null,
        formedDate: body.formedDate ? new Date(String(body.formedDate)) : null,
        isActive: true,
      },
    });
    return NextResponse.json({ committee });
  } catch {
    return NextResponse.json({ error: "Could not create committee" }, { status: 500 });
  }
}
