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

// Import models
const About = require("../models/aboutUs");
const Blog = require("../models/blog");
const Service = require("../models/service");
const Contact = require("../models/contact");
const Footer = require("../models/footer");
const Header = require("../models/header");
const HeaderMenu = require("../models/headerMenu");
const Home = require("../models/home");
const FAQ = require("../models/faq");
const Visa = require("../models/visa");
const Appointment = require("../models/appointment");
const Pricing = require("../models/pricing");
const Activity = require("../models/activity");

// Data mapping
const dataMap = {
  about: { model: About, file: "about.json" },
  blog: { model: Blog, file: "blog.json" },
  service: { model: Service, file: "service.json" },
  contact: { model: Contact, file: "contact.json" },
  footer: { model: Footer, file: "footer.json" },
  header: { model: Header, file: "header.json" },
  headerMenu: { model: HeaderMenu, file: "header-menu.json" },
  home: { model: Home, file: "home.json" },
  faq: { model: FAQ, file: "faq-data.json" },
  visa: { model: Visa, file: "visa.json" },
  appointment: { model: Appointment, file: "appointment.json" },
  pricing: { model: Pricing, file: "pricing.json" },
};

const seedDatabase = async () => {
  try {
    // Kết nối MongoDB
    if (!process.env.MONGODB_URI) {
      throw new Error("MONGODB_URI is not defined in environment variables");
    }
    
    console.log("🔗 Connecting to MongoDB...");
    await mongoose.connect(process.env.MONGODB_URI);
    console.log("✅ MongoDB Connected");

    // Seed từng collection
    for (const [key, config] of Object.entries(dataMap)) {
      try {
        const jsonPath = path.join(__dirname, "../data", config.file);
        
        if (!fs.existsSync(jsonPath)) {
          console.warn(`⚠️  ${config.file} không tồn tại, bỏ qua...`);
          continue;
        }

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

        if (Array.isArray(jsonData)) {
          // Nếu là array, xóa tất cả và thêm mới
          await config.model.deleteMany({});
          await config.model.insertMany(jsonData);
          console.log(`✅ Seeded ${key} (${jsonData.length} items)`);
        } else {
          // Nếu là object, dùng upsert
          await config.model.findOneAndUpdate({}, jsonData, { 
            upsert: true, 
            new: true,
            setDefaultsOnInsert: true 
          });
          console.log(`✅ Seeded ${key}`);
        }
      } catch (error) {
        console.error(`❌ Error seeding ${key}:`, error.message);
      }
    }

    console.log("🎉 Database seeding completed successfully!");

  } catch (error) {
    console.error("❌ Seeding failed:", error.message);
    process.exit(1);
  } finally {
    await mongoose.connection.close();
    console.log("👋 Database connection closed");
    process.exit(0);
  }
};

seedDatabase();
