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

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

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

  const notes = await prisma.patientNote.findMany({
    where: { leadId: id, clinicId: session.id },
    orderBy: { createdAt: "desc" },
  });
  return NextResponse.json(notes);
}

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

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

  const { type, content } = await req.json();
  if (!content?.trim()) return NextResponse.json({ error: "Content required" }, { status: 400 });

  const note = await prisma.patientNote.create({
    data: { leadId: id, clinicId: session.id, type: type || "note", content: content.trim() },
  });
  return NextResponse.json(note, { status: 201 });
}

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

  const noteId = req.nextUrl.searchParams.get("noteId");
  if (!noteId) return NextResponse.json({ error: "noteId required" }, { status: 400 });

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

  await prisma.patientNote.delete({ where: { id: noteId } });
  return NextResponse.json({ ok: true });
}
