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

export async function GET() {
  try {
    const tickets = await sql`
      SELECT 
        st.id, st.subject, st.category, st.priority, st.status, 
        st.created_at, st.updated_at,
        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
      ORDER BY 
        CASE st.priority 
          WHEN 'urgent' THEN 1 
          WHEN 'high' THEN 2 
          WHEN 'medium' THEN 3 
          ELSE 4 
        END,
        st.created_at DESC
    `

    return NextResponse.json({
      tickets: tickets.map((t: any) => ({
        id: t.id,
        subject: t.subject,
        user: {
          name: t.user_name || "Unknown User",
          email: t.user_email || "",
          avatar: t.user_avatar || "/placeholder.svg?height=32&width=32",
        },
        category: t.category || "general",
        priority: t.priority || "medium",
        status: t.status || "open",
        createdAt: new Date(t.created_at).toLocaleString("fr-FR"),
        lastReply: new Date(t.updated_at).toLocaleString("fr-FR"),
        messages: 1,
      })),
    })
  } catch (error) {
    console.error("Support tickets error:", error)
    return NextResponse.json({ error: "Failed to fetch tickets" }, { status: 500 })
  }
}

export async function PUT(request: Request) {
  try {
    const { id, status, assigned_to } = await request.json()

    await sql`
      UPDATE support_tickets
      SET 
        status = ${status},
        assigned_to = ${assigned_to || null},
        updated_at = NOW(),
        resolved_at = ${status === "resolved" || status === "closed" ? "NOW()" : null}
      WHERE id = ${id}
    `

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error updating ticket:", error)
    return NextResponse.json({ error: "Failed to update ticket" }, { status: 500 })
  }
}
