/**
 * Application Notes API
 * PATCH: Update application internal notes
 * GET: Get application notes history
 */

import { NextRequest, NextResponse } from "next/server";
import { getStaffSession } from "@/lib/staff-session";
import { prisma } from "@/lib/db";

export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    // Verify staff authentication
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Fetch notes from database
    const notes = await prisma.application_notes.findMany({
      where: { application_id: params.id },
      orderBy: { created_at: "desc" },
    });

    return NextResponse.json({
      success: true,
      notes: notes || [],
    });
  } catch (error: any) {
    console.error("Error fetching application notes:", error);
    return NextResponse.json(
      { error: "Failed to fetch notes", details: error.message },
      { status: 500 },
    );
  }
}

export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } },
) {
  try {
    // Verify staff authentication
    const session = await getStaffSession();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

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

    if (!noteText || !noteText.trim()) {
      return NextResponse.json(
        { error: "Note text is required" },
        { status: 400 },
      );
    }

    // Create new note entry
    const noteData = {
      application_id: params.id,
      staff_id: session.id,
      staff_name: session.name,
      note_text: noteText.trim(),
      created_at: new Date(),
      updated_at: new Date(),
    };

    // Save note to database
    const newNote = await prisma.application_notes.create({
      data: noteData,
    });

    return NextResponse.json({
      success: true,
      message: "Note added successfully",
      note: newNote,
    });
  } catch (error: any) {
    console.error("Error adding application note:", error);
    return NextResponse.json(
      { error: "Failed to add note", details: error.message },
      { status: 500 },
    );
  }
}
