require("dotenv").config();
const fs = require("fs").promises;
const path = require("path");
const connectDB = require("../config/database");

/**
 * Migration: import_home_content
 * Created: 19:00:00 2026-02-05
 * Description:
 *   Import nội dung trang Home từ file JSON (Next.js) vào MongoDB (model Home).
 *   Nguồn dữ liệu: hailearning.edu.vn/app/home.json
 */
async function migrate() {
  try {
    // 1) Connect DB
    await connectDB();
    console.log("🚀 Starting migration: import_home_content...");

    // 2) Load model
    const Home = require("../models/home");
    console.log("✅ Home model registered successfully");

    // 3) Load JSON data
    const dataPath = path.join(__dirname, "..", "..", "hailearning.edu.vn", "app", "home.json");
    const raw = await fs.readFile(dataPath, "utf8");
    const homeData = JSON.parse(raw);
    console.log("📖 Home data loaded from:", dataPath);

    // 4) Clear existing
    console.log("🧹 Clearing existing Home data...");
    await Home.deleteMany({});
    console.log("✅ Existing Home documents cleared");

    // 5) Insert new document
    const created = await Home.create(homeData);
    console.log("✅ Home document created with _id:", created._id.toString());

    console.log("🎉 Migration import_home_content completed successfully.");
    process.exit(0);
  } catch (err) {
    console.error("❌ Migration failed:", err);
    process.exit(1);
  }
}

migrate();

