import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/infrastructure/db/prisma";
import { withAuth, ROLES } from "@/middleware/auth";

export async function GET(request: NextRequest, { params }: { params: { phone: string } }) {
  const result = await withAuth(request, [ROLES.ASSISTANT, ROLES.THERAPIST]);

  if (result instanceof NextResponse) {
    return result;
  }

  const { user } = result;
  const { phone } = params;

  const notes = await prisma.clinicalNote.findMany({
    where: { patientId: phone },
    orderBy: { createdAt: "desc" },
  });

  return NextResponse.json({
    success: true,
    notes: notes.map((note) => ({
      id: note.id,
      patientId: note.patientId,
      content: note.content,
      tags: note.tags,
      createdAt: note.createdAt,
      updatedAt: note.updatedAt,
    })),
  });
}

export async function POST(request: NextRequest, { params }: { params: { phone: string } }) {
  const result = await withAuth(request, [ROLES.THERAPIST]);

  if (result instanceof NextResponse) {
    return result;
  }

  const { user } = result;
  const { phone } = params;
  const body = await request.json();

  if (!body.content) {
    return NextResponse.json({ error: "Content is required" }, { status: 400 });
  }

  try {
    const note = await prisma.clinicalNote.create({
      data: {
        patientId: phone,
        content: body.content,
        tags: body.tags,
      },
    });

    return NextResponse.json({
      success: true,
      note: {
        id: note.id,
        patientId: note.patientId,
        content: note.content,
        tags: note.tags,
        createdAt: note.createdAt,
      },
    });
  } catch (error) {
    console.error("Error creating note:", error);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
