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

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

const projectSchema = new mongoose.Schema({
  name: String,
  category: String,
});

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

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

    console.log("Finding projects without category...");
    const projectsWithoutCategory = await Project.find({
      $or: [
        { category: { $exists: false } },
        { category: null },
        { category: "" },
      ],
    });

    console.log(
      `Found ${projectsWithoutCategory.length} projects without category`
    );

    if (projectsWithoutCategory.length > 0) {
      console.log("Updating projects with default 'general' category...");
      const result = await Project.updateMany(
        {
          $or: [
            { category: { $exists: false } },
            { category: null },
            { category: "" },
          ],
        },
        { $set: { category: "general" } }
      );
      console.log(`Updated ${result.modifiedCount} projects`);
    }

    // Verify
    const allProjects = await Project.find({}).select("name category");
    console.log("\nAll projects:");
    allProjects.forEach((p) => {
      console.log(`  - ${p.name}: ${p.category || "NO CATEGORY"}`);
    });

    console.log("\n✅ Migration complete!");
  } catch (error) {
    console.error("❌ Error:", error);
  } finally {
    await mongoose.connection.close();
    console.log("Connection closed");
  }
}

fixProjectCategories();
