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

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

    const backups = await sql`
      SELECT * FROM backups ORDER BY created_at DESC LIMIT 50
    `

    const totalSize = backups.reduce((acc: number, b: any) => acc + (b.file_size || 0), 0)
    const lastBackup = backups.length > 0 ? backups[0].created_at : null

    return NextResponse.json({
      backups: backups.map((b: any) => ({
        ...b,
        size: formatBytes(b.file_size || 0),
        type: b.backup_type || "manual",
      })),
      stats: {
        total: backups.length,
        lastBackup,
        totalSize: formatBytes(totalSize),
        autoTime: "03:00",
      },
    })
  } catch (error) {
    console.error("Error fetching backups:", error)
    return NextResponse.json({
      backups: [],
      stats: { total: 0, lastBackup: null, totalSize: "0 GB", autoTime: "03:00" },
    })
  }
}

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

    const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)
    const name = `backup_${timestamp}_manual.sql`

    const tables = ["users", "tracks", "albums", "artists", "playlists", "genres", "categories"]
    let backupContent = `-- AfricanMusic Database Backup\n-- Created: ${new Date().toISOString()}\n\n`

    for (const table of tables) {
      try {
        const rows = await sql(`SELECT * FROM ${table}`)
        backupContent += `-- Table: ${table}\n`
        backupContent += `-- Rows: ${rows.length}\n\n`

        if (rows.length > 0) {
          const columns = Object.keys(rows[0])
          for (const row of rows) {
            const values = columns.map((col) => {
              const val = row[col]
              if (val === null) return "NULL"
              if (typeof val === "string") return `'${val.replace(/'/g, "''")}'`
              if (typeof val === "boolean") return val ? "true" : "false"
              if (val instanceof Date) return `'${val.toISOString()}'`
              return String(val)
            })
            backupContent += `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${values.join(", ")});\n`
          }
          backupContent += "\n"
        }
      } catch (e) {
        backupContent += `-- Table ${table} skipped (may not exist)\n\n`
      }
    }

    const blob = await put(`backups/${name}`, backupContent, {
      access: "public",
      contentType: "text/plain",
    })

    const result = await sql`
      INSERT INTO backups (name, description, file_url, file_size, backup_type, status, created_at, completed_at)
      VALUES (${name}, ${"Manual backup"}, ${blob.url}, ${backupContent.length}, ${"manual"}, ${"completed"}, NOW(), NOW())
      RETURNING *
    `

    return NextResponse.json({
      ...result[0],
      size: formatBytes(backupContent.length),
      type: "manual",
    })
  } catch (error) {
    console.error("Error creating backup:", error)
    return NextResponse.json({ error: "Failed to create backup" }, { status: 500 })
  }
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B"
  const k = 1024
  const sizes = ["B", "KB", "MB", "GB"]
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return `${Number.parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`
}
