import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get("userId")

    if (!userId) {
      return NextResponse.json({ error: "User ID required" }, { status: 400 })
    }

    const tickets = await sql`
      SELECT 
        st.*,
        (SELECT COUNT(*) FROM ticket_messages WHERE ticket_id = st.id) as message_count,
        (SELECT message FROM ticket_messages WHERE ticket_id = st.id ORDER BY created_at DESC LIMIT 1) as last_message
      FROM support_tickets st
      WHERE st.user_id = ${userId}
      ORDER BY st.created_at DESC
    `

    return NextResponse.json({ tickets })
  } catch (error) {
    console.error("Error fetching tickets:", error)
    return NextResponse.json({ error: "Failed to fetch tickets" }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const { userId, subject, category, priority, message } = await request.json()

    if (!userId || !subject || !message) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    const [ticket] = await sql`
      INSERT INTO support_tickets (user_id, subject, category, priority, status)
      VALUES (${userId}, ${subject}, ${category || "technical"}, ${priority || "medium"}, 'open')
      RETURNING *
    `

    await sql`
      INSERT INTO ticket_messages (ticket_id, user_id, message, is_staff_reply)
      VALUES (${ticket.id}, ${userId}, ${message}, false)
    `

    return NextResponse.json({ ticket })
  } catch (error) {
    console.error("Error creating ticket:", error)
    return NextResponse.json({ error: "Failed to create ticket" }, { status: 500 })
  }
}
