const mongoose = require("mongoose");
const dotenv = require("dotenv");
dotenv.config();

const Role = require("../models/roleModel");

const roles = [
  {
    name: "root",
    permissions: {
      Root: ["add", "edit", "delete", "view"],
      Admin: ["add", "edit", "delete", "view"],
      Users: ["add", "edit", "delete", "view"],
      Tasks: ["add", "edit", "delete", "view"],
    },
    isSystemRole: true,
  },
  {
    name: "admin",
    permissions: {
      Users: ["add", "edit", "view"],
      Tasks: ["add", "edit", "view"],
      Reports: ["view"],
    },
    isSystemRole: true,
  },
  {
    name: "manager",
    permissions: {
      Tasks: ["add", "edit", "view"],
      Users: ["view"],
    },
  },
  {
    name: "user",
    permissions: {
      Tasks: ["view"],
    },
  },
];

async function seedRoles() {
  try {
    await mongoose.connect( `mongodb://${process.env.DB_USER_NAME}:${process.env.DB_PASSWORD}@${process.env.MONGO_URI}/${process.env.DB_NAME}?authSource=admin`,);
    console.log("DB connected");

    for (const role of roles) {
      const exists = await Role.findOne({ name: role.name });
      if (!exists) {
        await Role.create(role);
        console.log(`Role created: ${role.name}`);
      }
    }

    console.log("✅ Role seeding completed");
    process.exit();
  } catch (err) {
    console.error("❌ Role seeding failed:", err);
    process.exit(1);
  }
}

seedRoles();
