// createAdmin.js
const dotenv = require("dotenv");
const mongoose = require("mongoose");
const User = require("./models/userModel");

dotenv.config({ path: "./config.env" });

const DB = `mongodb://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}?authSource=${process.env.DB_AUTH_SOURCE}&directConnection=true&ssl=false`;

(async () => {
  try {
    await mongoose.connect(DB);
    console.log("✅ DB connected...");

    const adminEmail = "ahmedyasser393923@gmail.com";
    const adminPassword = "Admin12345678#";

    const existingUser = await User.findOne({ email: adminEmail });
    if (existingUser) {
      console.log(`⚠️ User exists. Updating role...`);
      // 2. FIX: Use 'super-admin' (kebab-case) to match Model Enum
      existingUser.role = "super-admin";
      await existingUser.save({ validateBeforeSave: false });
      console.log("✅ Role updated to super-admin.");
      process.exit(0);
    }

    const newAdmin = await User.create({
      name: "Ahmed Yasser",
      email: adminEmail,
      gender: "male",
      password: adminPassword,
      passwordConfirm: adminPassword,
      role: "super-admin",
    });

    console.log("🎉 Super admin created:", newAdmin.email);
    process.exit(0);
  } catch (err) {
    console.error("❌ Error:", err.message);
    process.exit(1);
  }
})();
