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

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id: ticketId } = await params

    const [ticket] = await sql`
      SELECT 
        st.*,
        u.name as user_name, 
        u.email as user_email, 
        u.avatar_url as user_avatar
      FROM support_tickets st
      LEFT JOIN users u ON st.user_id = u.id
      WHERE st.id = ${ticketId}
    `

    if (!ticket) {
      return NextResponse.json({ error: "Ticket not found" }, { status: 404 })
    }

    const messages = await sql`
      SELECT 
        tm.*,
        u.name as user_name,
        u.avatar_url,
        u.role
      FROM ticket_messages tm
      LEFT JOIN users u ON tm.user_id = u.id
      WHERE tm.ticket_id = ${ticketId}
      ORDER BY tm.created_at ASC
    `

    return NextResponse.json({
      ticket: {
        ...ticket,
        user: {
          name: ticket.user_name || "Unknown User",
          email: ticket.user_email || "",
          avatar: ticket.user_avatar || "/placeholder.svg",
        },
      },
      messages,
    })
  } catch (error) {
    console.error("Error fetching ticket:", error)
    return NextResponse.json({ error: "Failed to fetch ticket" }, { status: 500 })
  }
}

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id: ticketId } = await params
    const { userId, message } = await request.json()

    const [newMessage] = await sql`
      INSERT INTO ticket_messages (ticket_id, user_id, message, is_staff_reply)
      VALUES (${ticketId}, ${userId}, ${message}, true)
      RETURNING *
    `

    await sql`
      UPDATE support_tickets
      SET status = 'waiting', updated_at = NOW()
      WHERE id = ${ticketId}
    `

    return NextResponse.json({ message: newMessage })
  } catch (error) {
    console.error("Error adding message:", error)
    return NextResponse.json({ error: "Failed to add message" }, { status: 500 })
  }
}
