/**
 * Migration: Convert About News static items to dynamic Blog selection
 * Date: 2026-02-07
 *
 * This migration:
 * 1. Adds selectedBlogIds field to About news section
 * 2. Keeps existing items for backward compatibility
 * 3. Does NOT delete old data (safe migration)
 */

const mongoose = require("mongoose");
require("dotenv").config();

const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/SIMS";

async function up() {
    try {
        await mongoose.connect(MONGODB_URI);
        console.log("✓ Connected to MongoDB");

        const AboutUs = mongoose.model("AboutUs", new mongoose.Schema({}, { strict: false }));

        const doc = await AboutUs.findOne();

        if (!doc) {
            console.log("⚠ No About Us document found. Skipping migration.");
            return;
        }

        // Check if already migrated
        if (doc.news && doc.news.selectedBlogIds !== undefined) {
            console.log("✓ Migration already applied. Skipping.");
            return;
        }

        // Add selectedBlogIds field (empty array by default)
        if (!doc.news) {
            doc.news = {};
        }

        doc.news.selectedBlogIds = [];

        // Keep existing items for backward compatibility
        // Admin can manually select blogs after migration

        await doc.save();

        console.log("✓ Migration completed successfully");
        console.log("  - Added selectedBlogIds field to About news section");
        console.log("  - Existing items preserved for backward compatibility");
        console.log("  - Admin can now select blogs from Blog Management");
    } catch (error) {
        console.error("✗ Migration failed:", error);
        throw error;
    }
}

async function down() {
    try {
        await mongoose.connect(MONGODB_URI);
        console.log("✓ Connected to MongoDB");

        const AboutUs = mongoose.model("AboutUs", new mongoose.Schema({}, { strict: false }));

        const doc = await AboutUs.findOne();

        if (!doc || !doc.news) {
            console.log("⚠ No About Us document found. Skipping rollback.");
            return;
        }

        // Remove selectedBlogIds field
        if (doc.news.selectedBlogIds !== undefined) {
            delete doc.news.selectedBlogIds;
            await doc.save();
            console.log("✓ Rollback completed - selectedBlogIds removed");
        } else {
            console.log("✓ Nothing to rollback");
        }
    } catch (error) {
        console.error("✗ Rollback failed:", error);
        throw error;
    }
}

// Run migration
if (require.main === module) {
    up()
        .then(() => {
            console.log("\n✓ Migration script completed");
            process.exit(0);
        })
        .catch((error) => {
            console.error("\n✗ Migration script failed:", error);
            process.exit(1);
        });
}

module.exports = { up, down };
