const mongoose = require('mongoose');
const fs = require('fs');
const path = require('path');
const AdmZip = require('adm-zip');
const connectDB = require('../config/db');
const User = require('../models/User');
const Asset = require('../models/Asset');
const Scene = require('../models/Scene');
const Hotspot = require('../models/Hotspot');
const Setting = require('../models/Setting');

const backup = async () => {
    await connectDB();
    const zip = new AdmZip();
    const uploadDir = path.join(__dirname, '../uploads');
    const backupPath = path.join(__dirname, `../backups/backup_${Date.now()}.zip`);
    
    if (!fs.existsSync(path.join(__dirname, '../backups'))) fs.mkdirSync(path.join(__dirname, '../backups'));

    console.log('Exporting Database...');
    const dbData = {
        users: await User.find().lean(),
        assets: await Asset.find().lean(),
        scenes: await Scene.find().lean(),
        hotspots: await Hotspot.find().lean(),
        settings: await Setting.find().lean()
    };
    zip.addFile("database.json", Buffer.from(JSON.stringify(dbData, null, 2), "utf8"));

    if (fs.existsSync(uploadDir)) {
        console.log('Adding Uploads...');
        zip.addLocalFolder(uploadDir, "uploads");
    }

    zip.writeZip(backupPath);
    console.log(`Backup completed: ${backupPath}`);
    mongoose.connection.close();
};

backup();