require("dotenv").config();
const mongoose = require("mongoose");
const bcrypt = require("bcryptjs");
const User = require("./models/userModel");

// MongoDB Connection
const MONGO_URI =
  process.env.MONGO_URI ||
  "mongodb+srv://ydubey48_db_user:xCHPPhz0d9ObcDmt@therapy.zbtsngk.mongodb.net/?retryWrites=true&w=majority&appName=Therapy";

async function createAdminUser() {
  try {
    await mongoose.connect(MONGO_URI, {
      useNewUrlParser: true,
    });
    console.log("✅ MongoDB Connected");

    // Check if admin user already exists
    const existingAdmin = await User.findOne({ role: "admin" });
    if (existingAdmin) {
      console.log("✅ Admin user already exists:");
      console.log("   Email:", existingAdmin.email);
      console.log("   Role:", existingAdmin.role);
      console.log("   ID:", existingAdmin._id);

      // Update role to admin if needed
      if (existingAdmin.role !== "admin") {
        existingAdmin.role = "admin";
        await existingAdmin.save();
        console.log("✅ Updated user role to admin");
      }

      mongoose.disconnect();
      return;
    }

    // Create new admin user
    const hashedPassword = await bcrypt.hash("admin123", 10);

    const adminUser = new User({
      fullname: "Admin User",
      email: "testadmin@gmail.com",
      mobile: "1234567890",
      countryCode: "+91",
      role: "admin",
      password: hashedPassword,
      isEmailVerified: true,
    });

    await adminUser.save();
    console.log("✅ Admin user created successfully:");
    console.log("   Email: admin@mending.com");
    console.log("   Password: admin123");
    console.log("   Role: admin");
    console.log("   ID:", adminUser._id);

    mongoose.disconnect();
  } catch (error) {
    console.error("❌ Error:", error);
    mongoose.disconnect();
  }
}

// Also check existing users and their roles
async function checkUsers() {
  try {
    await mongoose.connect(MONGO_URI, {
      useNewUrlParser: true,
    });
    console.log("✅ MongoDB Connected");

    const users = await User.find({}).select("fullname email role");
    console.log("\n📋 All users in database:");
    users.forEach((user) => {
      console.log(`   ${user.fullname} (${user.email}) - Role: ${user.role}`);
    });

    mongoose.disconnect();
  } catch (error) {
    console.error("❌ Error:", error);
    mongoose.disconnect();
  }
}

// Run based on command line argument
const command = process.argv[2];

if (command === "create") {
  createAdminUser();
} else if (command === "check") {
  checkUsers();
} else {
  console.log("Usage:");
  console.log("  node create-admin-user.js create  - Create admin user");
  console.log("  node create-admin-user.js check   - Check existing users");
}
