import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"
import { buildIcs } from "@/lib/ics"

export async function GET(_request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const { id } = await params

    const result = await query(
      `SELECT e.id, e.user_id, e.participant_id, e.title, e.description, e.event_type,
              e.start_time, e.end_time, e.duration_minutes, e.status,
              u.email AS user_email, u.first_name AS user_first, u.last_name AS user_last,
              p.email AS p_email, p.first_name AS p_first, p.last_name AS p_last
       FROM scheduled_events e
       JOIN users u ON u.id = e.user_id
       LEFT JOIN users p ON p.id = e.participant_id
       WHERE e.id = $1 AND e.user_id = $2`,
      [id, user.id],
    )

    if (result.rows.length === 0) {
      return NextResponse.json({ error: "Event not found" }, { status: 404 })
    }

    const r = result.rows[0]

    const icsContent = buildIcs({
      uid: r.id,
      title: r.title,
      description: r.description || undefined,
      startTime: new Date(r.start_time),
      endTime: r.end_time ? new Date(r.end_time) : undefined,
      durationMinutes: r.duration_minutes || undefined,
      organizerName: `${r.user_first} ${r.user_last}`,
      organizerEmail: r.user_email,
      attendeeName: r.p_first ? `${r.p_first} ${r.p_last}` : undefined,
      attendeeEmail: r.p_email || undefined,
    })

    return new NextResponse(icsContent, {
      headers: {
        "Content-Type": "text/calendar; charset=utf-8",
        "Content-Disposition": `attachment; filename="event-${r.id}.ics"`,
      },
    })
  } catch (error) {
    console.error("ICS GET error:", error)
    return NextResponse.json({ error: "Failed to generate calendar file" }, { status: 500 })
  }
}
