import { NextRequest, NextResponse } from 'next/server'
import * as fs from 'fs'
import * as path from 'path'
import * as zlib from 'zlib'
import { promisify } from 'util'

const gunzip = promisify(zlib.gunzip)

const DATA_DIR = path.join(process.cwd(), 'docs/infrastructure/data')
const BACKUP_DIR = path.join(process.cwd(), 'docs/infrastructure/backups')

export async function POST(request: NextRequest) {
  try {
    const { filename } = await request.json()

    if (!filename) {
      return NextResponse.json({ error: 'Filename is required' }, { status: 400 })
    }

    const backupPath = path.join(BACKUP_DIR, filename)

    if (!fs.existsSync(backupPath)) {
      return NextResponse.json({ error: 'Backup file not found' }, { status: 404 })
    }

    // Read and decompress backup
    const compressed = fs.readFileSync(backupPath)
    const decompressed = await gunzip(compressed)
    const backup = JSON.parse(decompressed.toString())

    // Restore files
    for (const [file, data] of Object.entries(backup)) {
      const filePath = path.join(DATA_DIR, file)
      fs.writeFileSync(filePath, JSON.stringify(data, null, 2))
    }

    return NextResponse.json({
      success: true,
      filesRestored: Object.keys(backup).length,
      timestamp: new Date().toISOString(),
    })
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to restore backup',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

