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

/** Chart of accounts: income / expense heads with usage stats. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const heads = await prisma.accountHead.findMany({
    where: { institutionId: session.institutionId },
    orderBy: [{ type: "asc" }, { name: "asc" }],
    include: {
      _count: { select: { entries: true } },
      entries: { select: { type: true, amount: true } },
    },
  });

  return NextResponse.json({
    heads: heads.map(({ entries, ...head }) => ({
      ...head,
      entryCount: head._count.entries,
      total: entries.reduce((s, e) => s + Number(e.amount), 0),
    })),
  });
}

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();
    const nameBn = String(body.nameBn ?? "").trim() || null;
    const type = String(body.type ?? "");

    if (!name || !["INCOME", "EXPENSE"].includes(type)) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    const exists = await prisma.accountHead.findFirst({
      where: { institutionId: session.institutionId, name },
    });
    if (exists) return NextResponse.json({ error: "NAME_EXISTS" }, { status: 409 });

    const head = await prisma.accountHead.create({
      data: { institutionId: session.institutionId, name, nameBn, type: type as never },
    });
    return NextResponse.json({ head });
  } catch {
    return NextResponse.json({ error: "Could not create head" }, { status: 500 });
  }
}
