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

export async function PUT(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;
  const body = await req.json();

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

  const updated = await prisma.treatment.update({
    where: { id },
    data: {
      name: body.name ?? treatment.name,
      duration: body.duration ?? treatment.duration,
      price: body.price !== undefined ? body.price : treatment.price,
      prepInstructions: body.prepInstructions !== undefined ? body.prepInstructions : treatment.prepInstructions,
      aftercareInstructions: body.aftercareInstructions !== undefined ? body.aftercareInstructions : treatment.aftercareInstructions,
    },
  });

  return NextResponse.json(updated);
}

export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
  const session = await getSession();
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { id } = await params;

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

  // Soft delete — just deactivate
  await prisma.treatment.update({
    where: { id },
    data: { isActive: false },
  });

  return NextResponse.json({ ok: true });
}
