const mongoose = require("mongoose");
const path = require("path");
const fs = require("fs");

// Import model
const Footer = require("../models/footer");

/**
 * Migration script để import dữ liệu footer từ JSON
 */
async function up() {
    try {
        console.log("Starting footer migration...");

        // Đọc dữ liệu từ file JSON
        const jsonPath = path.join(__dirname, "../data/footer.json");

        if (!fs.existsSync(jsonPath)) {
            throw new Error("Footer JSON file not found");
        }

        const footerData = JSON.parse(fs.readFileSync(jsonPath, "utf8"));

        // Sử dụng static method từ model để migrate
        const result = await Footer.migrateFromJson(footerData);

        console.log("Footer migration completed successfully");
        return result;
    } catch (error) {
        console.error("Footer migration failed:", error);
        throw error;
    }
}

/**
 * Rollback migration
 */
async function down() {
    try {
        console.log("Rolling back footer migration...");

        // Xóa footer data
        await Footer.deleteMany({});

        console.log("Footer rollback completed");
    } catch (error) {
        console.error("Footer rollback failed:", error);
        throw error;
    }
}

module.exports = { up, down };

// Chạy migration nếu file được gọi trực tiếp
if (require.main === module) {
    const connectDB = require("../config/database");

    connectDB()
        .then(() => up())
        .then(() => {
            console.log("Migration completed successfully");
            process.exit(0);
        })
        .catch((error) => {
            console.error("Migration failed:", error);
            process.exit(1);
        });
}
