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 te.*,
              r.first_name || ' ' || r.last_name AS resource_name
       FROM time_entries te
       LEFT JOIN resources r ON r.id = te.resource_id
       WHERE te.ticket_id = $1
       ORDER BY te.entry_date DESC`,
      [id]
    );

    const timeEntries = result.rows.map((row) => ({
      id: Number(row.id),
      hoursWorked: row.hours_worked ? parseFloat(row.hours_worked) : 0,
      dateWorked: row.entry_date,
      summaryNotes: row.notes,
      resourceName: row.resource_name ?? null,
      billable: row.billable,
    }));

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