import { NextRequest, NextResponse } from 'next/server';
import { postgresClient } from '@/lib/services/postgres-client';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const result = await postgresClient.query(
      `SELECT n.*,
              r.first_name || ' ' || r.last_name AS creator_name
       FROM ticket_notes n
       LEFT JOIN resources r ON r.id = n.creator_resource_id
       WHERE n.ticket_id = $1
         AND (n.is_deleted = false OR n.is_deleted IS NULL)
       ORDER BY n.create_date_time DESC`,
      [id]
    );

    const notes = result.rows.map((row) => ({
      id: Number(row.id),
      noteType: row.note_type,
      title: row.title,
      description: row.description,
      createDateTime: row.create_date_time,
      creatorResourceId: row.creator_resource_id ? Number(row.creator_resource_id) : null,
      creatorName: row.creator_name ?? null,
      publish: row.publish,
    }));

    return NextResponse.json({ notes });
  } catch (error) {
    console.error('Error fetching ticket notes:', error);
    return NextResponse.json(
      { error: 'Failed to fetch ticket notes' },
      { status: 500 }
    );
  }
}
