import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getSession } from "@/lib/auth";

export async function POST(req: NextRequest) {
  try {
    const session = await getSession();
    if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { treeId } = await req.json();
    if (!treeId) return NextResponse.json({ error: "No treeId provided" }, { status: 400 });

    const tree = await prisma.reminderTree.findUnique({ where: { id: treeId } });
    if (!tree) return NextResponse.json({ error: "Tree not found" }, { status: 404 });
    if (tree.clinicId !== session.id) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const nodeCount = await prisma.treeNode.count({ where: { treeId } });
    if (nodeCount === 0) return NextResponse.json({ error: "Tree has no nodes — save first" }, { status: 400 });

    // Activate this tree, deactivate others of the same triggerType
    await prisma.reminderTree.updateMany({
      where: { clinicId: session.id, triggerType: tree.triggerType, id: { not: treeId } },
      data: { isActive: false },
    });

    await prisma.reminderTree.update({
      where: { id: treeId },
      data: { isActive: true },
    });

    return NextResponse.json({
      success: true,
      message: `Tree "${tree.name}" is now LIVE for trigger "${tree.triggerType}"`,
    });
  } catch (err: any) {
    console.error("Deploy error:", err);
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
