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 restore = async () => {
    const zipPath = process.argv[2];
    if (!zipPath) return console.error('Please provide zip file path: node restoreData.js <path>');

    await connectDB();
    const zip = new AdmZip(zipPath);
    const dbEntry = zip.getEntry("database.json");
    const uploadDir = path.join(__dirname, '../uploads');

    console.log('Restoring Database...');
    const dbData = JSON.parse(dbEntry.getData().toString('utf8'));

    await Promise.all([
        User.deleteMany({}), Asset.deleteMany({}), Scene.deleteMany({}),
        Hotspot.deleteMany({}), Setting.deleteMany({})
    ]);

    await Promise.all([
        User.insertMany(dbData.users), Asset.insertMany(dbData.assets),
        Scene.insertMany(dbData.scenes), Hotspot.insertMany(dbData.hotspots),
        Setting.insertMany(dbData.settings)
    ]);

    console.log('Restoring Files...');
    zip.extractEntryTo("uploads/", uploadDir, false, true);

    console.log('Restore completed successfully!');
    mongoose.connection.close();
};

restore();