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

/** Institution profile: the institution manages its own info. */
export async function GET() {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const institution = await prisma.institution.findUnique({
    where: { id: session.institutionId },
    select: {
      id: true, name: true, code: true, type: true, email: true, phone: true,
      address: true, district: true, subDistrict: true, logo: true, website: true, description: true,
      eiin: true, ein: true, mpoCode: true, boardCode: true, educationBoard: true,
      establishedYear: true, postCode: true,
      status: true, createdAt: true,
    },
  });
  if (!institution) return NextResponse.json({ error: "Not found" }, { status: 404 });
  return NextResponse.json({ institution });
}

export async function PUT(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 phone = String(body.phone ?? "").trim();
    const address = String(body.address ?? "").trim();
    const district = String(body.district ?? "").trim() || null;
    const subDistrict = String(body.subDistrict ?? "").trim() || null;
    const website = String(body.website ?? "").trim() || null;
    const description = String(body.description ?? "").trim() || null;
    // Bangladesh education-registry identifiers (Institution Info)
    const eiin = String(body.eiin ?? "").trim() || null;
    const ein = String(body.ein ?? "").trim() || null;
    const mpoCode = String(body.mpoCode ?? "").trim() || null;
    const boardCode = String(body.boardCode ?? "").trim() || null;
    const educationBoard = String(body.educationBoard ?? "").trim() || null;
    const establishedYear = Number(body.establishedYear) || null;
    const postCode = String(body.postCode ?? "").trim() || null;
    let logo: string | null | undefined = body.logo;
    if (logo !== undefined && logo !== null && !String(logo).startsWith("data:image/")) {
      return NextResponse.json({ error: "Invalid logo" }, { status: 400 });
    }

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

    const institution = await prisma.institution.update({
      where: { id: session.institutionId },
      data: {
        name, phone, address, district, subDistrict, website, description,
        eiin, ein, mpoCode, boardCode, educationBoard, establishedYear, postCode,
        ...(logo !== undefined ? { logo } : {}),
      },
    });
    return NextResponse.json({ institution });
  } catch {
    return NextResponse.json({ error: "Could not update profile" }, { status: 500 });
  }
}
