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

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

export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  try {
    const body = await req.json();
    const name = String(body.name ?? "").trim();
    const nameBn = String(body.nameBn ?? "").trim() || name;
    const institutionType = String(body.institutionType ?? "");
    const price = Number(body.price);
    const durationMonths = Number(body.durationMonths) || 12;
    const maxStudents = Number(body.maxStudents);
    const features = String(body.features ?? "")
      .split("\n")
      .map((s) => s.trim())
      .filter(Boolean);
    const featuresBn = String(body.featuresBn ?? "")
      .split("\n")
      .map((s) => s.trim())
      .filter(Boolean);

    if (!name || !Number.isFinite(price) || price <= 0 || !Number.isFinite(maxStudents)) {
      return NextResponse.json({ error: "Invalid package data" }, { status: 400 });
    }
    if (!INSTITUTION_TYPES.includes(institutionType as never)) {
      return NextResponse.json({ error: "Invalid institution type" }, { status: 400 });
    }

    const plan = await prisma.packagePlan.update({
      where: { id: Number(id) },
      data: {
        name,
        nameBn,
        institutionType: institutionType as never,
        price,
        durationMonths,
        maxStudents,
        features,
        featuresBn: featuresBn.length ? featuresBn : features,
        billingBasis: body.billingBasis ? String(body.billingBasis) : null,
        ratePerStudent:
          body.ratePerStudent !== undefined && body.ratePerStudent !== null && body.ratePerStudent !== ""
            ? Number(body.ratePerStudent)
            : null,
        yearlyDiscountPct:
          body.yearlyDiscountPct === null || body.yearlyDiscountPct === undefined || body.yearlyDiscountPct === ""
            ? null
            : Number(body.yearlyDiscountPct),
      },
    });
    return NextResponse.json({ plan });
  } catch {
    return NextResponse.json({ error: "Could not update package" }, { status: 500 });
  }
}

export async function PATCH(req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const body = await req.json().catch(() => ({}));
  const isActive = Boolean(body.isActive);

  try {
    const plan = await prisma.packagePlan.update({
      where: { id: Number(id) },
      data: { isActive },
    });
    return NextResponse.json({ plan });
  } catch {
    return NextResponse.json({ error: "Could not update package" }, { status: 500 });
  }
}

export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const planId = Number(id);

  const [requestCount, subscriptionCount] = await Promise.all([
    prisma.packageRequest.count({ where: { packagePlanId: planId } }),
    prisma.subscription.count({ where: { packagePlanId: planId } }),
  ]);

  if (requestCount > 0 || subscriptionCount > 0) {
    return NextResponse.json({ error: "IN_USE" }, { status: 409 });
  }

  try {
    await prisma.packagePlan.delete({ where: { id: planId } });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not delete package" }, { status: 500 });
  }
}
