import { NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getPortalSession, isPortalError } from "../portal-utils"

export async function GET() {
  const session = await getPortalSession()
  if (isPortalError(session)) return session

  if (!session.customerId) {
    return NextResponse.json({ events: [] })
  }

  const milestones = await query(
    `SELECT m.id, m.name, m.status, m.progress, m.updated_at, p.name as project_name,
            'milestone' as event_type
     FROM milestones m
     JOIN projects p ON p.id = m.project_id
     WHERE p.customer_id = $1 AND p.deleted_at IS NULL
     ORDER BY m.updated_at DESC NULLS LAST
     LIMIT 20`,
    [session.customerId],
  )

  const invoices = await query(
    `SELECT i.id, i.invoice_number, i.total_amount, i.currency, s.name as status_name,
            i.updated_at, 'invoice' as event_type
     FROM invoices i
     LEFT JOIN invoice_statuses s ON s.id = i.status_id
     WHERE i.customer_id = $1
     ORDER BY i.updated_at DESC NULLS LAST
     LIMIT 20`,
    [session.customerId],
  )

  const tickets = await query(
    `SELECT id, title, status, created_at, 'ticket' as event_type
     FROM bug_reports
     WHERE reported_by = $1
     ORDER BY created_at DESC
     LIMIT 20`,
    [session.userId],
  )

  const events = [
    ...milestones.rows.map((r: Record<string, unknown>) => ({ ...r, date: r.updated_at })),
    ...invoices.rows.map((r: Record<string, unknown>) => ({ ...r, date: r.updated_at })),
    ...tickets.rows.map((r: Record<string, unknown>) => ({ ...r, date: r.created_at })),
  ].sort((a, b) => new Date(b.date as string).getTime() - new Date(a.date as string).getTime()).slice(0, 30)

  return NextResponse.json({ events })
}
