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 projectSchema = new mongoose.Schema({
  name: String,
  category: String,
  members: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
  createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
});

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

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

    // Get all users and projects
    const users = await User.find({}).lean();
    const projects = await Project.find({})
      .populate("members", "fullName email category")
      .lean();

    console.log("=".repeat(80));
    console.log("PROJECT VISIBILITY REPORT");
    console.log("=".repeat(80));

    console.log(`\nTotal Users: ${users.length}`);
    console.log(`Total Projects: ${projects.length}\n`);

    // Show user categories
    console.log("USERS BY CATEGORY:");
    console.log("-".repeat(80));
    const usersByCategory = {};
    users.forEach((u) => {
      const cat = u.category || "NO CATEGORY";
      if (!usersByCategory[cat]) usersByCategory[cat] = [];
      usersByCategory[cat].push(u);
    });

    Object.entries(usersByCategory).forEach(([cat, userList]) => {
      console.log(`\n${cat}:`);
      userList.forEach((u) => {
        console.log(`  - ${u.fullName} (${u.email}) - ${u.role}`);
      });
    });

    // Show projects and who can see them
    console.log("\n" + "=".repeat(80));
    console.log("PROJECTS AND VISIBILITY:");
    console.log("=".repeat(80));

    projects.forEach((p) => {
      console.log(`\n📁 ${p.name}`);
      console.log(`   Category: ${p.category || "NO CATEGORY"}`);
      console.log(`   Assigned Members: ${p.members?.length || 0}`);
      if (p.members && p.members.length > 0) {
        p.members.forEach((m) => {
          console.log(`     - ${m.fullName} (${m.category || "no category"})`);
        });
      }

      // Calculate who can see this project
      console.log(`   👁️  VISIBLE TO:`);

      // Admins always see everything
      const admins = users.filter((u) => u.role === "admin");
      console.log(`     - All ${admins.length} admin(s)`);

      // Employees in the same category
      if (p.category) {
        const categoryEmployees = users.filter(
          (u) => u.role !== "admin" && u.category === p.category
        );
        if (categoryEmployees.length > 0) {
          console.log(
            `     - ${categoryEmployees.length} employee(s) in ${p.category} category:`
          );
          categoryEmployees.forEach((e) => {
            console.log(`       • ${e.fullName}`);
          });
        } else {
          console.log(`     - ⚠️  NO employees in ${p.category} category!`);
        }
      }

      // Members of the project (regardless of category)
      if (p.members && p.members.length > 0) {
        console.log(
          `     - ${p.members.length} assigned member(s) (any category)`
        );
      }
    });

    // Check for issues
    console.log("\n" + "=".repeat(80));
    console.log("POTENTIAL ISSUES:");
    console.log("=".repeat(80));

    const usersWithoutCategory = users.filter(
      (u) => !u.category && u.role !== "admin"
    );
    if (usersWithoutCategory.length > 0) {
      console.log(
        `\n⚠️  ${usersWithoutCategory.length} non-admin users WITHOUT category:`
      );
      usersWithoutCategory.forEach((u) => {
        console.log(`   - ${u.fullName} (${u.email}) - ${u.role}`);
      });
    }

    const projectsWithoutCategory = projects.filter((p) => !p.category);
    if (projectsWithoutCategory.length > 0) {
      console.log(
        `\n⚠️  ${projectsWithoutCategory.length} projects WITHOUT category:`
      );
      projectsWithoutCategory.forEach((p) => {
        console.log(`   - ${p.name}`);
      });
    }

    if (
      usersWithoutCategory.length === 0 &&
      projectsWithoutCategory.length === 0
    ) {
      console.log(
        "\n✅ No issues found! All users and projects have categories."
      );
    }

    console.log("\n" + "=".repeat(80));
    console.log("END OF REPORT");
    console.log("=".repeat(80) + "\n");
  } catch (error) {
    console.error("❌ Error:", error);
  } finally {
    await mongoose.connection.close();
    console.log("Connection closed");
  }
}

checkProjectVisibility();
