const mongoose = require("mongoose");
const path = require("path");
require("dotenv").config({ path: path.join(__dirname, "../.env") });

const Header = require("../models/header");
const headerData = require("../data/header.json");

const migrateHeader = async () => {
    try {
        const mongoUri = process.env.MONGODB_URI;
        if (!mongoUri) {
            throw new Error("MONGODB_URI not found in environment variables");
        }
        await mongoose.connect(mongoUri);
        console.log("Connected to MongoDB");

        // Delete existing header
        await Header.deleteMany({});
        console.log("Cleared existing headers");

        // Transform and insert data
        const headerDocument = {
            top: {
                phone: headerData.top?.phone || "",
                email: headerData.top?.email || "",
                location: headerData.top?.location || "",
                socialLinks: (headerData.top?.socialLinks || []).map((link, idx) => ({
                    ...link,
                    order: idx,
                })),
                languages: headerData.top?.languages || [],
            },
            offcanvas: headerData.offcanvas || {},
            menu: (headerData.menu || []).map((item, idx) => ({
                ...item,
                order: idx,
                children:
                    item.children?.map((child, childIdx) => ({
                        ...child,
                        order: childIdx,
                        children:
                            child.children?.map((subchild, subIdx) => ({
                                ...subchild,
                                order: subIdx,
                            })) || [],
                    })) || [],
            })),
            logo: {
                light: "/assets/img/logo/white-logo.svg",
                dark: "/assets/img/logo/black-logo.svg",
                alt: "Hai Learning",
            },
            ctaButton: {
                label: "Get Started",
                href: "/contact",
                style: "primary",
            },
            status: "active",
            order: 1,
        };

        const result = await Header.create(headerDocument);
        console.log("Header migrated successfully:", result._id);

        await mongoose.connection.close();
        process.exit(0);
    } catch (error) {
        console.error("Migration error:", error);
        process.exit(1);
    }
};

migrateHeader();
