import mongoose from "mongoose";
import "dotenv/config";

const MONGODB_URI =
  process.env.MONGODB_URI || "mongodb://localhost:27017/office-crm";

const userSchema = new mongoose.Schema({
  fullName: String,
  email: String,
  role: String,
  category: String,
});

const User = mongoose.model("User", userSchema);

async function assignCategoriesToUsers() {
  try {
    console.log("Connecting to MongoDB...");
    await mongoose.connect(MONGODB_URI);
    console.log("Connected!\n");

    const users = await User.find({ category: { $exists: false } });
    console.log(`Found ${users.length} users without categories\n`);

    if (users.length === 0) {
      console.log("✅ All users already have categories!");
      return;
    }

    // Assign "general" category to users without one
    const result = await User.updateMany(
      {
        $or: [
          { category: { $exists: false } },
          { category: null },
          { category: "" },
        ],
      },
      { $set: { category: "general" } }
    );

    console.log(
      `✅ Updated ${result.modifiedCount} users with "general" category\n`
    );

    // Show updated users
    const allUsers = await User.find({}).select("fullName email role category");
    console.log("All users after update:");
    console.log("=".repeat(80));
    allUsers.forEach((u) => {
      console.log(`${u.fullName} (${u.email})`);
      console.log(
        `  Role: ${u.role} | Category: ${u.category || "NO CATEGORY"}\n`
      );
    });

    console.log(
      "\n💡 TIP: Admin can now assign specific categories to employees via Users screen"
    );
  } catch (error) {
    console.error("❌ Error:", error);
  } finally {
    await mongoose.connection.close();
    console.log("\nConnection closed");
  }
}

assignCategoriesToUsers();
