import { type NextRequest, NextResponse } from "next/server"
import { getAdminUser } from "@/lib/admin-auth"
import { sql } from "@/lib/db"

const RESERVED_PATHS = ["stats", "downloads", "catalog", "logs"]

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

  if (RESERVED_PATHS.includes(id)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 })
  }

  const userId = await getAdminUser(request)

  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  try {
    const result = await sql`
      SELECT 
        id, name, company, api_key, api_secret, status, permissions,
        rate_limit, requests_count, last_used_at, expires_at,
        created_at, notes, country_code, operator_code,
        pricing_tier, callback_url, webhook_secret
      FROM external_api_keys
      WHERE id = ${id}
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "API key not found" }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      data: result[0],
    })
  } catch (error) {
    console.error("Error fetching API key:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params

  if (RESERVED_PATHS.includes(id)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 })
  }

  const userId = await getAdminUser(request)

  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  try {
    const body = await request.json()
    const { status, rate_limit, notes, callback_url, name, company } = body

    const result = await sql`
      UPDATE external_api_keys
      SET 
        status = COALESCE(${status}, status),
        rate_limit = COALESCE(${rate_limit}, rate_limit),
        notes = COALESCE(${notes}, notes),
        callback_url = COALESCE(${callback_url}, callback_url),
        name = COALESCE(${name}, name),
        company = COALESCE(${company}, company),
        updated_at = NOW()
      WHERE id = ${id}
      RETURNING id, name, company, status, rate_limit
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "API key not found" }, { status: 404 })
    }

    return NextResponse.json({
      success: true,
      data: result[0],
    })
  } catch (error) {
    console.error("Error updating API key:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params

  if (RESERVED_PATHS.includes(id)) {
    return NextResponse.json({ error: "Not found" }, { status: 404 })
  }

  const userId = await getAdminUser(request)

  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  try {
    await sql`
      DELETE FROM external_api_keys
      WHERE id = ${id}
    `

    return NextResponse.json({
      success: true,
    })
  } catch (error) {
    console.error("Error deleting API key:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
