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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const ticketId = parseInt(id);
  if (isNaN(ticketId)) return NextResponse.json({ error: 'Invalid id' }, { status: 400 });

  const [ticketRow, notes, timeEntries] = await Promise.all([
    postgresClient.query(`
      SELECT t.id, t.ticket_number, t.title, t.description, t.status, t.priority,
             t.create_date, t.last_activity_date, t.due_date_time, t.resolved_date_time,
             t.queue_id, q.label as queue_label,
             t.estimated_hours, t.resolution,
             c.company_name,
             r.first_name || ' ' || r.last_name as assigned_to
      FROM tickets t
      LEFT JOIN companies c ON c.id = t.company_id
      LEFT JOIN queues q ON q.value = t.queue_id
      LEFT JOIN resources r ON r.id = t.assigned_resource_id
      WHERE t.id = $1 AND t.is_deleted = false
    `, [ticketId]),

    postgresClient.query(`
      SELECT n.id, n.title, n.description, n.note_type, n.publish,
             n.create_date_time,
             r.first_name || ' ' || r.last_name as author,
             (n.note_type IN (13, 91, 93, 94, 99, 101)) AS is_system
      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
      ORDER BY n.create_date_time ASC
    `, [ticketId]),

    postgresClient.query(`
      SELECT te.id, te.entry_date, te.hours_worked, te.notes, te.billable,
             te.start_date_time, te.end_date_time,
             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 ASC, te.start_date_time ASC
    `, [ticketId]),
  ]);

  if (!ticketRow.rows[0]) return NextResponse.json({ error: 'Not found' }, { status: 404 });

  const ticket = ticketRow.rows[0];

  // Merge notes and time entries into a single chronological timeline
  type TimelineItem =
    | { kind: 'created'; ts: string; ticket: typeof ticket }
    | { kind: 'note'; ts: string; data: typeof notes.rows[0]; is_system: boolean }
    | { kind: 'time'; ts: string; data: typeof timeEntries.rows[0] }
    | { kind: 'resolved'; ts: string };

  const timeline: TimelineItem[] = [];

  timeline.push({ kind: 'created', ts: ticket.create_date, ticket });

  for (const n of notes.rows) {
    timeline.push({ kind: 'note', ts: n.create_date_time, data: n, is_system: n.is_system });
  }
  for (const te of timeEntries.rows) {
    timeline.push({ kind: 'time', ts: te.entry_date, data: te });
  }
  if (ticket.resolved_date_time) {
    timeline.push({ kind: 'resolved', ts: ticket.resolved_date_time });
  }

  timeline.sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime());

  const totalHours = timeEntries.rows.reduce((s, r) => s + parseFloat(r.hours_worked ?? 0), 0);

  return NextResponse.json({ ticket, timeline, total_hours: Math.round(totalHours * 10) / 10 });
}
