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

export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const admissions = await prisma.admission.findMany({
    where: { institutionId: session.institutionId },
    orderBy: { createdAt: "desc" },
    include: {
      classItem: { select: { name: true, nameBn: true } },
      sessionItem: { select: { name: true, nameBn: true } },
      student: { select: { id: true, roll: true } },
    },
  });

  return NextResponse.json({
    admissions: admissions.map((a) => ({
      ...a,
      applicationType: a.applicationType,
      feeAmount: Number(a.feeAmount),
    })),
  });
}

/** Create a new admission application (optionally with an applicant message). */
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 studentName = String(body.studentName ?? "").trim();
    const guardianPhone = String(body.guardianPhone ?? "").trim();
    const note = String(body.note ?? "").trim() || null;
    const applicationType = body.applicationType === "RAPID" ? "RAPID" : "DETAILS";
    // Rapid applications carry no guardian name — default it to the student name
    const guardianName = String(body.guardianName ?? "").trim() || studentName;

    if (!studentName || !guardianPhone) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    // snapshot the Control Panel admission-fee setting onto this application
    const settings = await prisma.institution.findUnique({
      where: { id: session.institutionId },
      select: { admissionFeeEnabled: true, admissionFeeAmount: true },
    });
    const feeAmount =
      settings?.admissionFeeEnabled && Number(settings.admissionFeeAmount) > 0
        ? Number(settings.admissionFeeAmount)
        : 0;

    const admission = await prisma.$transaction(async (tx) => {
      const created = await tx.admission.create({
        data: {
          institutionId: session.institutionId!,
          studentName,
          applicationType,
          studentNameBn: String(body.studentNameBn ?? "").trim() || null,
          gender: ["MALE", "FEMALE", "OTHER"].includes(body.gender) ? body.gender : "MALE",
          dob: body.dob ? new Date(body.dob) : null,
          guardianName,
          guardianNameBn: String(body.guardianNameBn ?? "").trim() || null,
          guardianPhone,
          motherName: String(body.motherName ?? "").trim() || null,
          motherNameBn: String(body.motherNameBn ?? "").trim() || null,
          email: String(body.email ?? "").trim() || null,
          address: String(body.address ?? "").trim() || null,
          permanentAddress: String(body.permanentAddress ?? "").trim() || null,
          studentPhone: String(body.studentPhone ?? "").trim() || null,
          bloodGroup: String(body.bloodGroup ?? "").trim() || null,
          religion: String(body.religion ?? "").trim() || null,
          classItemId: body.classItemId ? Number(body.classItemId) : null,
          sessionItemId: body.sessionItemId ? Number(body.sessionItemId) : null,
          note,
          feeAmount,
          feeStatus: feeAmount > 0 ? "DUE" : "NONE",
        },
      });
      // An application note becomes the first (applicant) message in the thread
      if (note) {
        await tx.message.create({
          data: {
            institutionId: session.institutionId!,
            admissionId: created.id,
            sender: "APPLICANT",
            senderName: guardianName,
            body: note,
          },
        });
      }
      return created;
    });

    return NextResponse.json({ admission });
  } catch {
    return NextResponse.json({ error: "Could not create application" }, { status: 500 });
  }
}
