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

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

/** Update a pricing slab (range, price, yearly discount, active). */
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;
  try {
    const body = await req.json();
    const existing = await prisma.pricingTier.findUnique({ where: { id: Number(id) } });
    if (!existing) return NextResponse.json({ error: "NOT_FOUND" }, { status: 404 });

    const minStudents = body.minStudents !== undefined ? Number(body.minStudents) : existing.minStudents;
    const maxRaw =
      body.maxStudents === undefined
        ? existing.maxStudents
        : body.maxStudents === "" || body.maxStudents === null
          ? null
          : Number(body.maxStudents);
    const monthlyPrice = body.monthlyPrice !== undefined ? Number(body.monthlyPrice) : Number(existing.monthlyPrice);
    const yearlyDiscount =
      body.yearlyDiscount !== undefined ? Number(body.yearlyDiscount) : Number(existing.yearlyDiscount);

    if (!Number.isFinite(minStudents) || minStudents < 0) {
      return NextResponse.json({ error: "INVALID_RANGE" }, { status: 400 });
    }
    if (maxRaw !== null && (!Number.isFinite(maxRaw) || maxRaw <= minStudents)) {
      return NextResponse.json({ error: "INVALID_RANGE" }, { status: 400 });
    }
    if (!Number.isFinite(monthlyPrice) || monthlyPrice <= 0) {
      return NextResponse.json({ error: "INVALID_PRICE" }, { status: 400 });
    }
    if (!Number.isFinite(yearlyDiscount) || yearlyDiscount < 0 || yearlyDiscount > 90) {
      return NextResponse.json({ error: "INVALID_DISCOUNT" }, { status: 400 });
    }

    const tier = await prisma.pricingTier.update({
      where: { id: Number(id) },
      data: {
        minStudents,
        maxStudents: maxRaw,
        monthlyPrice,
        yearlyDiscount,
        ...(body.active !== undefined ? { active: Boolean(body.active) } : {}),
        ...(body.sortOrder !== undefined ? { sortOrder: Number(body.sortOrder) || 0 } : {}),
      },
    });
    return NextResponse.json({ tier });
  } catch {
    return NextResponse.json({ error: "Could not update tier" }, { 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;
  try {
    await prisma.pricingTier.delete({ where: { id: Number(id) } });
    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ error: "Could not delete tier" }, { status: 500 });
  }
}
