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

export async function GET() {
  try {
    const apiKeys = await sql`
      SELECT * FROM api_keys ORDER BY created_at DESC
    `
    return NextResponse.json(apiKeys)
  } catch (error) {
    console.error("Error fetching API keys:", error)
    return NextResponse.json([])
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { name, permissions } = body

    // Generate a random API key
    const key =
      "sk_live_" +
      Array(32)
        .fill(0)
        .map(() => Math.random().toString(36).charAt(2))
        .join("")

    const result = await sql`
      INSERT INTO api_keys (name, key_hash, permissions)
      VALUES (${name}, ${key}, ${JSON.stringify(permissions)})
      RETURNING *
    `
    return NextResponse.json({ ...result[0], key })
  } catch (error) {
    console.error("Error creating API key:", error)
    return NextResponse.json({ error: "Failed to create API key" }, { status: 500 })
  }
}
