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

export async function GET(request: NextRequest) {
  const userId = await getAdminUser(request)
  if (!userId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  try {
    const { searchParams } = new URL(request.url)
    const format = searchParams.get("format") || "json"

    const tracks = await sql`
      SELECT 
        t.id,
        t.title,
        t.artist_name,
        t.genre,
        t.duration_ms as duration,
        COALESCE(t.ringtone_price, 1.00) as default_price,
        t.cover_url,
        t.audio_url,
        t.total_streams as popularity,
        t.release_date,
        t.created_at
      FROM tracks t
      WHERE t.ringtone_enabled = true
      ORDER BY t.total_streams DESC
    `

    if (format === "csv") {
      const headers = ["ID", "Title", "Artist", "Genre", "Duration", "Price", "Popularity", "Cover URL", "Audio URL"]
      const rows = tracks.map((t: any) => [
        t.id,
        `"${(t.title || "").replace(/"/g, '""')}"`,
        `"${(t.artist_name || "").replace(/"/g, '""')}"`,
        t.genre || "",
        t.duration || 0,
        t.default_price || 1.0,
        t.popularity || 0,
        t.cover_url || "",
        t.audio_url || "",
      ])

      const csv = [headers.join(","), ...rows.map((r) => r.join(","))].join("\n")

      return new NextResponse(csv, {
        headers: {
          "Content-Type": "text/csv",
          "Content-Disposition": `attachment; filename="africanmusic-ringtones-catalog-${Date.now()}.csv"`,
        },
      })
    }

    if (format === "xml") {
      const escapeXml = (str: string) => {
        return (str || "").replace(/[<>&'"]/g, (c) => {
          switch (c) {
            case "<":
              return "&lt;"
            case ">":
              return "&gt;"
            case "&":
              return "&amp;"
            case "'":
              return "&apos;"
            case '"':
              return "&quot;"
            default:
              return c
          }
        })
      }

      const xml = `<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <metadata>
    <generated>${new Date().toISOString()}</generated>
    <total_tracks>${tracks.length}</total_tracks>
    <provider>AfricanMusic</provider>
  </metadata>
  <tracks>
    ${tracks
      .map(
        (t: any) => `
    <track id="${t.id}">
      <title>${escapeXml(t.title)}</title>
      <artist>${escapeXml(t.artist_name)}</artist>
      <genre>${escapeXml(t.genre)}</genre>
      <duration>${t.duration || 0}</duration>
      <price>${t.default_price || 1.0}</price>
      <popularity>${t.popularity || 0}</popularity>
      <cover_url>${escapeXml(t.cover_url)}</cover_url>
      <audio_url>${escapeXml(t.audio_url)}</audio_url>
      <release_date>${t.release_date || ""}</release_date>
    </track>`,
      )
      .join("")}
  </tracks>
</catalog>`

      return new NextResponse(xml, {
        headers: {
          "Content-Type": "application/xml",
          "Content-Disposition": `attachment; filename="africanmusic-ringtones-catalog-${Date.now()}.xml"`,
        },
      })
    }

    return NextResponse.json({
      success: true,
      metadata: {
        generated: new Date().toISOString(),
        total_tracks: tracks.length,
        provider: "AfricanMusic",
        format: "json",
      },
      tracks: tracks.map((t: any) => ({
        id: t.id,
        title: t.title,
        artist: t.artist_name,
        genre: t.genre,
        duration: t.duration,
        price: t.default_price || 1.0,
        currency: "USD",
        cover_url: t.cover_url,
        audio_url: t.audio_url,
        popularity: t.popularity,
        release_date: t.release_date,
      })),
    })
  } catch (error) {
    console.error("Error exporting catalog:", error)
    return NextResponse.json({ error: "Failed to export catalog" }, { status: 500 })
  }
}
