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

export async function GET(request: NextRequest) {
  const userId = await getAdminUser(request)

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

  try {
    const apiKeys = await sql`
      SELECT 
        id, name, company, api_key, status, permissions,
        rate_limit, requests_count, last_used_at, expires_at,
        created_at, notes, country_code, operator_code,
        pricing_tier, callback_url
      FROM external_api_keys
      ORDER BY created_at DESC
    `

    return NextResponse.json({
      success: true,
      data: apiKeys,
    })
  } catch (error) {
    console.error("Error fetching API keys:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  const userId = await getAdminUser(request)

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

  try {
    const body = await request.json()
    const {
      name,
      company,
      rateLimit = 1000,
      expiresIn,
      notes,
      country_code,
      operator_code,
      pricing_tier = "standard",
      callback_url,
    } = body

    const apiKey = "africanmusic_" + crypto.randomBytes(32).toString("hex")
    const apiSecret = "secret_" + crypto.randomBytes(32).toString("hex")
    const webhookSecret = "whsec_" + crypto.randomBytes(24).toString("hex")

    let expiresAt = null
    if (expiresIn && expiresIn !== "never") {
      const now = new Date()
      if (expiresIn === "1month") expiresAt = new Date(now.setMonth(now.getMonth() + 1))
      else if (expiresIn === "6months") expiresAt = new Date(now.setMonth(now.getMonth() + 6))
      else if (expiresIn === "1year") expiresAt = new Date(now.setFullYear(now.getFullYear() + 1))
    }

    const result = await sql`
      INSERT INTO external_api_keys (
        name, company, api_key, api_secret, status, permissions,
        rate_limit, expires_at, created_by, notes,
        country_code, operator_code, pricing_tier, callback_url, webhook_secret
      )
      VALUES (
        ${name}, ${company}, ${apiKey}, ${apiSecret}, 'active',
        '["ringtone:read", "ringtone:download", "track:search"]'::jsonb,
        ${rateLimit}, ${expiresAt}, ${userId}, ${notes || null},
        ${country_code || null}, ${operator_code || null}, ${pricing_tier}, 
        ${callback_url || null}, ${webhookSecret}
      )
      RETURNING id, api_key, api_secret
    `

    return NextResponse.json({
      success: true,
      data: {
        id: result[0].id,
        apiKey: result[0].api_key,
        apiSecret: result[0].api_secret,
        webhookSecret,
      },
    })
  } catch (error) {
    console.error("Error creating API key:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  const userId = await getAdminUser(request)

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

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

    if (!id) {
      return NextResponse.json({ error: "API key ID required" }, { status: 400 })
    }

    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),
        updated_at = NOW()
      WHERE id = ${id}
      RETURNING id, status
    `

    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) {
  const userId = await getAdminUser(request)

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

  try {
    const { searchParams } = new URL(request.url)
    const id = searchParams.get("id")

    if (!id) {
      return NextResponse.json({ error: "API key ID required" }, { status: 400 })
    }

    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 })
  }
}
