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

async function verifyApiKey(apiKey: string) {
  try {
    const result = await sql`
      SELECT id, name, company, permissions, rate_limit, requests_count, status, expires_at,
             country_code, operator_code, pricing_tier
      FROM external_api_keys
      WHERE api_key = ${apiKey}
      AND status = 'active'
      AND (expires_at IS NULL OR expires_at > NOW())
    `

    if (result.length === 0) {
      return null
    }

    await sql`
      UPDATE external_api_keys
      SET last_used_at = NOW(),
          requests_count = requests_count + 1,
          updated_at = NOW()
      WHERE api_key = ${apiKey}
    `

    return result[0]
  } catch (error) {
    console.error("[API] Error verifying API key:", error)
    return null
  }
}

async function logApiUsage(
  apiKeyId: string,
  endpoint: string,
  method: string,
  statusCode: number,
  responseTime: number,
  ipAddress: string,
  userAgent: string,
  requestBody?: any,
  errorMessage?: string,
) {
  try {
    await sql`
      INSERT INTO api_usage_logs (
        api_key_id, endpoint, method, status_code, response_time,
        ip_address, user_agent, request_body, error_message
      )
      VALUES (
        ${apiKeyId}, ${endpoint}, ${method}, ${statusCode}, ${responseTime},
        ${ipAddress}, ${userAgent}, ${requestBody ? JSON.stringify(requestBody) : null}, ${errorMessage || null}
      )
    `
  } catch (error) {
    console.error("[API] Error logging usage:", error)
  }
}

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const startTime = Date.now()
  const { id } = await params
  const apiKey = request.headers.get("x-api-key")
  const ipAddress = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "unknown"
  const userAgent = request.headers.get("user-agent") || "unknown"

  if (!apiKey) {
    return NextResponse.json({ error: "API key required", code: "AUTH_REQUIRED" }, { status: 401 })
  }

  const apiKeyData = await verifyApiKey(apiKey)

  if (!apiKeyData) {
    return NextResponse.json({ error: "Invalid or expired API key", code: "INVALID_KEY" }, { status: 401 })
  }

  const permissions = apiKeyData.permissions as string[]
  if (!permissions.includes("ringtone:read")) {
    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "GET",
      403,
      Date.now() - startTime,
      ipAddress,
      userAgent,
    )
    return NextResponse.json({ error: "Insufficient permissions", code: "FORBIDDEN" }, { status: 403 })
  }

  try {
    const tracks = await sql`
      SELECT 
        t.id,
        t.title,
        t.duration_ms as duration,
        t.audio_url,
        t.cover_url,
        t.total_streams as play_count,
        t.ringtone_price as price,
        a.name as artist_name,
        t.artist_id
      FROM tracks t
      LEFT JOIN artists a ON t.artist_id = a.id
      WHERE t.id = ${id}
      AND t.status = 'published'
      AND t.ringtone_enabled = true
    `

    if (tracks.length === 0) {
      await logApiUsage(
        apiKeyData.id,
        `/api/v1/ringtones/${id}`,
        "GET",
        404,
        Date.now() - startTime,
        ipAddress,
        userAgent,
      )
      return NextResponse.json({ error: "Ringtone not found", code: "NOT_FOUND" }, { status: 404 })
    }

    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "GET",
      200,
      Date.now() - startTime,
      ipAddress,
      userAgent,
    )

    return NextResponse.json({
      success: true,
      data: tracks[0],
    })
  } catch (error) {
    console.error("Error fetching ringtone:", error)
    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "GET",
      500,
      Date.now() - startTime,
      ipAddress,
      userAgent,
      null,
      String(error),
    )
    return NextResponse.json({ error: "Internal server error", code: "SERVER_ERROR" }, { status: 500 })
  }
}

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const startTime = Date.now()
  const { id } = await params
  const apiKey = request.headers.get("x-api-key")
  const ipAddress = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "unknown"
  const userAgent = request.headers.get("user-agent") || "unknown"

  if (!apiKey) {
    return NextResponse.json({ error: "API key required", code: "AUTH_REQUIRED" }, { status: 401 })
  }

  const apiKeyData = await verifyApiKey(apiKey)

  if (!apiKeyData) {
    return NextResponse.json({ error: "Invalid or expired API key", code: "INVALID_KEY" }, { status: 401 })
  }

  const permissions = apiKeyData.permissions as string[]
  if (!permissions.includes("ringtone:download")) {
    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "POST",
      403,
      Date.now() - startTime,
      ipAddress,
      userAgent,
    )
    return NextResponse.json({ error: "Insufficient permissions", code: "FORBIDDEN" }, { status: 403 })
  }

  try {
    const body = await request.json()
    const {
      customer_phone,
      msisdn,
      subscriber_id,
      transaction_id,
      country_code,
      currency = "USD",
      source = "api",
    } = body

    // Validate required fields
    if (!customer_phone && !msisdn) {
      await logApiUsage(
        apiKeyData.id,
        `/api/v1/ringtones/${id}`,
        "POST",
        400,
        Date.now() - startTime,
        ipAddress,
        userAgent,
        body,
      )
      return NextResponse.json(
        {
          error: "customer_phone or msisdn is required",
          code: "VALIDATION_ERROR",
        },
        { status: 400 },
      )
    }

    // Get track info
    const tracks = await sql`
      SELECT id, ringtone_price, title, audio_url
      FROM tracks
      WHERE id = ${id}
      AND ringtone_enabled = true
      AND status = 'published'
    `

    if (tracks.length === 0) {
      await logApiUsage(
        apiKeyData.id,
        `/api/v1/ringtones/${id}`,
        "POST",
        404,
        Date.now() - startTime,
        ipAddress,
        userAgent,
        body,
      )
      return NextResponse.json({ error: "Ringtone not found or not enabled", code: "NOT_FOUND" }, { status: 404 })
    }

    const track = tracks[0]
    const price = track.ringtone_price || 1.0

    // Calculate revenue share (70% platform, 30% operator by default)
    const platformShare = price * 0.7
    const operatorShare = price * 0.3

    // Generate unique transaction ID if not provided
    const txnId = transaction_id || `TXN-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`

    // Record the download with full tracking
    const downloadResult = await sql`
      INSERT INTO ringtone_downloads (
        track_id, api_key_id, operator_name, customer_phone,
        customer_msisdn, customer_country, subscriber_id, transaction_id,
        price, currency, operator_share, platform_share,
        status, delivery_status, ip_address, user_agent, request_source
      )
      VALUES (
        ${id}, ${apiKeyData.id}, ${apiKeyData.company},
        ${customer_phone || msisdn}, ${msisdn || customer_phone}, 
        ${country_code || apiKeyData.country_code}, ${subscriber_id},
        ${txnId}, ${price}, ${currency}, ${operatorShare}, ${platformShare},
        'completed', 'pending', ${ipAddress}, ${userAgent}, ${source}
      )
      RETURNING id
    `

    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "POST",
      200,
      Date.now() - startTime,
      ipAddress,
      userAgent,
      body,
    )

    // Return download URL with token
    const downloadToken = Buffer.from(`${downloadResult[0].id}:${Date.now()}`).toString("base64")

    return NextResponse.json({
      success: true,
      data: {
        download_id: downloadResult[0].id,
        track_id: track.id,
        title: track.title,
        transaction_id: txnId,
        price,
        currency,
        customer_phone: customer_phone || msisdn,
        download_url: `${process.env.NEXT_PUBLIC_APP_URL || "https://africanmusic.online"}/api/v1/ringtones/${track.id}/download?token=${downloadToken}&key=${apiKey}`,
        expires_in: 3600, // URL valid for 1 hour
      },
    })
  } catch (error: any) {
    console.error("Error recording ringtone download:", error)

    // Check for duplicate transaction
    if (error.code === "23505") {
      return NextResponse.json(
        {
          error: "Duplicate transaction ID",
          code: "DUPLICATE_TRANSACTION",
        },
        { status: 409 },
      )
    }

    await logApiUsage(
      apiKeyData.id,
      `/api/v1/ringtones/${id}`,
      "POST",
      500,
      Date.now() - startTime,
      ipAddress,
      userAgent,
      null,
      String(error),
    )
    return NextResponse.json({ error: "Internal server error", code: "SERVER_ERROR" }, { status: 500 })
  }
}
