import { d as db, b as backups, s as storageConfig } from '../../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq, desc } from 'drizzle-orm';
import path from 'path';
import { c as createStorageProvider } from '../../delete/_backupId_/DELETE-CSeC5rJf.js';
import { g as getBackupsDir } from '../../../auth/setup/POST-DYMc2GPx.js';
import zlib from 'zlib';
import { promisify } from 'util';
import fs from 'fs';

const gzip = promisify(zlib.gzip);
const gunzip = promisify(zlib.gunzip);
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
async function compressBuffer(buffer, options = {}) {
  const startTime = Date.now();
  const originalSize = buffer.length;
  const compressed = await gzip(buffer, {
    level: options.level || 6,
    // Default: balanced compression
    memLevel: options.memLevel || 8
  });
  const compressedSize = compressed.length;
  const compressionRatio = (originalSize - compressedSize) / originalSize * 100;
  const compressionTime = Date.now() - startTime;
  return {
    compressed,
    result: {
      originalSize,
      compressedSize,
      compressionRatio,
      compressionTime
    }
  };
}
async function decompressBuffer(buffer) {
  return await gunzip(buffer);
}
async function compressFile(inputPath, outputPath, options = {}) {
  const buffer = await readFile(inputPath);
  const { compressed, result } = await compressBuffer(buffer, options);
  await writeFile(outputPath, compressed);
  return result;
}
function getRecommendedCompressionLevel(fileSize) {
  if (fileSize < 1024 * 1024) return 9;
  if (fileSize < 100 * 1024 * 1024) return 6;
  return 3;
}

async function handler(req, res) {
  try {
    const { backupId } = req.params;
    const { deviceId } = req.query;
    if (!backupId) {
      return res.status(400).json({
        success: false,
        error: "Backup ID is required"
      });
    }
    if (!deviceId) {
      return res.status(400).json({
        success: false,
        error: "Device ID is required for authorization"
      });
    }
    const backup = await db.select().from(backups).where(eq(backups.backupId, backupId)).limit(1);
    if (backup.length === 0) {
      return res.status(404).json({
        success: false,
        error: "Backup not found"
      });
    }
    const backupRecord = backup[0];
    if (backupRecord.deviceId !== deviceId) {
      return res.status(403).json({
        success: false,
        error: "Unauthorized: Backup belongs to different device"
      });
    }
    const configs = await db.select().from(storageConfig).where(eq(storageConfig.isActive, true)).orderBy(desc(storageConfig.createdAt)).limit(1);
    let storageType = "local";
    let storageConfigData = { basePath: getBackupsDir() };
    if (configs.length > 0) {
      storageType = configs[0].storageType;
      storageConfigData = JSON.parse(configs[0].config);
    }
    const storageProvider = createStorageProvider({
      type: storageType,
      config: storageConfigData
    });
    const storagePath = backupRecord.filePath;
    if (!storagePath) {
      return res.status(404).json({
        success: false,
        error: "Backup file path not found"
      });
    }
    const exists = await storageProvider.exists(storagePath);
    if (!exists) {
      return res.status(404).json({
        success: false,
        error: "Backup file not found in storage"
      });
    }
    let fileBuffer = await storageProvider.download(storagePath);
    let fileName = path.basename(storagePath);
    if (backupRecord.compressed && backupRecord.compressionAlgorithm === "gzip") {
      try {
        console.log(`Decompressing backup: ${fileName}`);
        fileBuffer = await decompressBuffer(fileBuffer);
        if (fileName.endsWith(".gz")) {
          fileName = fileName.slice(0, -3);
        }
        console.log(`Decompressed backup successfully`);
      } catch (decompressError) {
        console.error("Decompression failed:", decompressError);
        return res.status(500).json({
          success: false,
          error: "Failed to decompress backup file",
          message: String(decompressError)
        });
      }
    }
    res.setHeader("Content-Type", "application/octet-stream");
    res.setHeader("Content-Length", fileBuffer.length);
    res.setHeader("Content-Disposition", `attachment; filename="${fileName}"`);
    res.send(fileBuffer);
  } catch (error) {
    console.error("Backup download error:", error);
    res.status(500).json({
      success: false,
      error: "Failed to download backup",
      message: String(error)
    });
  }
}

export { compressFile as c, getRecommendedCompressionLevel as g, handler as h };
