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

// Verify API key middleware
async function verifyApiKey(apiKey: string) {
  const result = await sql`
    SELECT id, name, company, permissions, rate_limit, requests_count, status, expires_at
    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
  }

  // Update last used and request count
  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]
}

// Log API usage
async function logApiUsage(
  apiKeyId: string,
  endpoint: string,
  method: string,
  statusCode: number,
  responseTime: number,
  ipAddress: string,
  userAgent: string,
) {
  await sql`
    INSERT INTO api_usage_logs (
      api_key_id, endpoint, method, status_code, response_time,
      ip_address, user_agent
    )
    VALUES (
      ${apiKeyId}, ${endpoint}, ${method}, ${statusCode}, ${responseTime},
      ${ipAddress}, ${userAgent}
    )
  `
}

export async function GET(request: NextRequest) {
  const startTime = Date.now()
  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 })
  }

  // Check rate limit
  if (apiKeyData.requests_count >= apiKeyData.rate_limit) {
    await logApiUsage(apiKeyData.id, "/api/v1/ringtones", "GET", 429, Date.now() - startTime, ipAddress, userAgent)
    return NextResponse.json({ error: "Rate limit exceeded", code: "RATE_LIMITED" }, { status: 429 })
  }

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

  try {
    const { searchParams } = new URL(request.url)
    const search = searchParams.get("search") || ""
    const genre = searchParams.get("genre") || ""
    const limit = Math.min(Number.parseInt(searchParams.get("limit") || "20"), 100)
    const offset = Number.parseInt(searchParams.get("offset") || "0")
    const format = searchParams.get("format") || "json" // json, csv, xml

    let tracks

    if (search && genre) {
      tracks = await sql`
        SELECT 
          t.id,
          t.title,
          t.duration_ms as duration,
          t.cover_url,
          t.total_streams as play_count,
          COALESCE(t.ringtone_price, 1.00) as price,
          a.name as artist_name,
          t.artist_id,
          g.name as genre
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN track_genres tg ON t.id = tg.track_id
        LEFT JOIN genres g ON tg.genre_id = g.id
        WHERE t.status = 'published'
        AND t.ringtone_enabled = true
        AND (
          t.title ILIKE ${"%" + search + "%"}
          OR a.name ILIKE ${"%" + search + "%"}
        )
        AND g.name ILIKE ${"%" + genre + "%"}
        ORDER BY t.total_streams DESC
      `
    } else if (search) {
      tracks = await sql`
        SELECT 
          t.id,
          t.title,
          t.duration_ms as duration,
          t.cover_url,
          t.total_streams as play_count,
          COALESCE(t.ringtone_price, 1.00) 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.status = 'published'
        AND t.ringtone_enabled = true
        AND (
          t.title ILIKE ${"%" + search + "%"}
          OR a.name ILIKE ${"%" + search + "%"}
        )
        ORDER BY t.total_streams DESC
      `
    } else if (genre) {
      tracks = await sql`
        SELECT 
          t.id,
          t.title,
          t.duration_ms as duration,
          t.cover_url,
          t.total_streams as play_count,
          COALESCE(t.ringtone_price, 1.00) as price,
          a.name as artist_name,
          t.artist_id,
          g.name as genre
        FROM tracks t
        LEFT JOIN artists a ON t.artist_id = a.id
        LEFT JOIN track_genres tg ON t.id = tg.track_id
        LEFT JOIN genres g ON tg.genre_id = g.id
        WHERE t.status = 'published'
        AND t.ringtone_enabled = true
        AND g.name ILIKE ${"%" + genre + "%"}
        ORDER BY t.total_streams DESC
      `
    } else {
      tracks = await sql`
        SELECT 
          t.id,
          t.title,
          t.duration_ms as duration,
          t.cover_url,
          t.total_streams as play_count,
          COALESCE(t.ringtone_price, 1.00) 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.status = 'published'
        AND t.ringtone_enabled = true
        ORDER BY t.total_streams DESC
      `
    }

    const total = tracks.length
    const paginatedTracks = tracks.slice(offset, offset + limit)

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

    if (format === "csv") {
      const header = "id,title,artist_name,duration,price,play_count\n"
      const rows = paginatedTracks
        .map(
          (t: any) =>
            `${t.id},"${t.title}","${t.artist_name || ""}",${t.duration || 0},${t.price},${t.play_count || 0}`,
        )
        .join("\n")
      return new NextResponse(header + rows, {
        headers: {
          "Content-Type": "text/csv",
          "Content-Disposition": "attachment; filename=ringtones.csv",
        },
      })
    }

    if (format === "xml") {
      const xml = `<?xml version="1.0" encoding="UTF-8"?>
<ringtones total="${total}" limit="${limit}" offset="${offset}">
${paginatedTracks
  .map(
    (t: any) => `  <ringtone>
    <id>${t.id}</id>
    <title><![CDATA[${t.title}]]></title>
    <artist><![CDATA[${t.artist_name || ""}]]></artist>
    <duration>${t.duration || 0}</duration>
    <price>${t.price}</price>
    <play_count>${t.play_count || 0}</play_count>
  </ringtone>`,
  )
  .join("\n")}
</ringtones>`
      return new NextResponse(xml, {
        headers: {
          "Content-Type": "application/xml",
        },
      })
    }

    return NextResponse.json({
      success: true,
      data: paginatedTracks,
      meta: {
        total,
        limit,
        offset,
        company: apiKeyData.company,
      },
    })
  } catch (error) {
    console.error("Error fetching ringtones:", error)
    await logApiUsage(apiKeyData.id, "/api/v1/ringtones", "GET", 500, Date.now() - startTime, ipAddress, userAgent)
    return NextResponse.json({ error: "Internal server error", code: "SERVER_ERROR" }, { status: 500 })
  }
}
