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 gzip = promisify(zlib.gzip)

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 {
    // Ensure backup directory exists
    if (!fs.existsSync(BACKUP_DIR)) {
      fs.mkdirSync(BACKUP_DIR, { recursive: true })
    }

    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const backupFilename = `backup-${timestamp}.json.gz`
    const backupPath = path.join(BACKUP_DIR, backupFilename)

    // Read all data files
    const files = fs.readdirSync(DATA_DIR).filter((f) => f.endsWith('.json'))
    const backup: Record<string, any> = {}

    for (const file of files) {
      const filePath = path.join(DATA_DIR, file)
      const content = fs.readFileSync(filePath, 'utf-8')
      backup[file] = JSON.parse(content)
    }

    // Compress and save
    const jsonData = JSON.stringify(backup, null, 2)
    const compressed = await gzip(jsonData)
    fs.writeFileSync(backupPath, compressed)

    return NextResponse.json({
      success: true,
      filename: backupFilename,
      timestamp: new Date().toISOString(),
      files: files.length,
    })
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to create backup',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

export async function GET() {
  try {
    if (!fs.existsSync(BACKUP_DIR)) {
      return NextResponse.json({ backups: [] })
    }

    const files = fs
      .readdirSync(BACKUP_DIR)
      .filter((f) => f.endsWith('.json.gz'))
      .map((f) => {
        const filePath = path.join(BACKUP_DIR, f)
        const stats = fs.statSync(filePath)
        return {
          filename: f,
          size: stats.size,
          created: stats.birthtime.toISOString(),
        }
      })
      .sort((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())

    return NextResponse.json({ backups: files })
  } catch (error) {
    return NextResponse.json(
      {
        error: 'Failed to list backups',
        message: error instanceof Error ? error.message : 'Unknown error',
      },
      { status: 500 }
    )
  }
}

