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

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

/** Update a book (copies adjustment keeps availability consistent). */
export async function PUT(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  try {
    const body = await req.json();
    const book = await prisma.book.findFirst({
      where: { id: Number(id), institutionId: session.institutionId },
    });
    if (!book) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const title = String(body.title ?? book.title).trim();
    const author = String(body.author ?? book.author).trim();
    const totalCopies = Math.max(1, Number(body.totalCopies) || book.totalCopies);
    if (!title || !author) {
      return NextResponse.json({ error: "Missing fields" }, { status: 400 });
    }

    // Keep availability within bounds when copy count changes
    const issued = book.totalCopies - book.availableCopies;
    if (totalCopies < issued) {
      return NextResponse.json({ error: "COPIES_IN_USE" }, { status: 400 });
    }

    await prisma.book.update({
      where: { id: book.id },
      data: {
        title,
        titleBn: body.titleBn !== undefined ? String(body.titleBn).trim() || null : book.titleBn,
        author,
        publisher: body.publisher !== undefined ? String(body.publisher).trim() || null : book.publisher,
        isbn: body.isbn !== undefined ? String(body.isbn).trim() || null : book.isbn,
        category: BOOK_CATEGORIES.includes(body.category as never) ? body.category : book.category,
        shelf: body.shelf !== undefined ? String(body.shelf).trim() || null : book.shelf,
        totalCopies,
        availableCopies: totalCopies - issued,
        price: body.price !== undefined ? Number(body.price) : book.price,
      },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not update book" }, { status: 500 });
  }
}

/** Delete a book (only when it has no issue history). */
export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await params;

  const book = await prisma.book.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!book) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const issues = await prisma.bookIssue.count({ where: { bookId: book.id } });
  if (issues > 0) return NextResponse.json({ error: "IN_USE" }, { status: 409 });

  await prisma.book.delete({ where: { id: book.id } });
  return NextResponse.json({ success: true });
}
