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

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

/** Post a support update: { message, isSolution? }.
    Replying to an OPEN ticket moves it to IN_PROGRESS; an update marked as
    solution resolves the ticket. */
export async function POST(req: Request, { params }: Params) {
  const session = await requireRole("SUPER_ADMIN");
  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const ticket = await prisma.supportTicket.findFirst({
    where: { id: Number(id) },
    select: { id: true, status: true },
  });
  if (!ticket) return NextResponse.json({ error: "Not found" }, { status: 404 });

  try {
    const body = await req.json();
    const message = String(body.message ?? "").trim();
    const isSolution = !!body.isSolution;
    if (!message) return NextResponse.json({ error: "Missing fields" }, { status: 400 });

    const created = await prisma.supportTicketMessage.create({
      data: {
        ticketId: ticket.id,
        senderRole: "SUPER_ADMIN",
        senderName: session.name,
        message,
        isSolution,
      },
    });
    // working-on-it reply / explicit solution
    const nextStatus = isSolution ? "RESOLVED" : ticket.status === "OPEN" ? "IN_PROGRESS" : ticket.status;
    if (nextStatus !== ticket.status) {
      await prisma.supportTicket.update({ where: { id: ticket.id }, data: { status: nextStatus } });
    }
    return NextResponse.json({ message: created });
  } catch {
    return NextResponse.json({ error: "Could not post update" }, { status: 500 });
  }
}
