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

export async function GET() {
  try {
    const logs = await sql`
      SELECT 
        al.id, al.action, al.entity_type, al.entity_id, al.details, al.ip_address, al.created_at,
        u.name as admin_name, u.email as admin_email
      FROM admin_logs al
      LEFT JOIN users u ON al.admin_id = u.id
      ORDER BY al.created_at DESC
      LIMIT 100
    `

    return NextResponse.json({
      logs: logs.map((l: any) => ({
        id: l.id,
        action: l.action,
        entityType: l.entity_type,
        entityId: l.entity_id,
        details: l.details,
        user: l.admin_name || "System",
        email: l.admin_email || "",
        ip: l.ip_address || "N/A",
        timestamp: new Date(l.created_at).toLocaleString("fr-FR"),
        level: l.action?.includes("error") ? "error" : l.action?.includes("delete") ? "warning" : "info",
      })),
    })
  } catch (error) {
    console.error("Logs error:", error)
    return NextResponse.json({ error: "Failed to fetch logs" }, { status: 500 })
  }
}
