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

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

    const { id } = await params
    const result = await sql`SELECT * FROM backups WHERE id = ${id}`

    if (result.length === 0) {
      return NextResponse.json({ error: "Backup not found" }, { status: 404 })
    }

    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error fetching backup:", error)
    return NextResponse.json({ error: "Failed to fetch backup" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { id } = await params

    const backup = await sql`SELECT * FROM backups WHERE id = ${id}`
    if (backup.length > 0 && backup[0].file_url) {
      try {
        await del(backup[0].file_url)
      } catch (e) {
        console.error("Error deleting blob:", e)
      }
    }

    await sql`DELETE FROM backups WHERE id = ${id}`
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error deleting backup:", error)
    return NextResponse.json({ error: "Failed to delete backup" }, { status: 500 })
  }
}
