const mongoose = require("mongoose");
const Role = require("../models/Role");
const Module = require("../models/Module");
require("dotenv").config();

mongoose.connect(process.env.MONGODB_URI);

const seedRolePermission = async () => {
  try {
    const ROLE_ID = "69689c0c7e85b81cc56af595"; // ✅ paste role _id here

    // get all modules
    const modules = await Module.find().select("_id name actions");

    const modulePermissions = modules
      .map((module) => {
        let permissions = {};

        // ✅ Manual conditions (STATIC)
        switch (module.name) {

          case "companies":
            permissions = {
              read: true,
              create: false,
              edit: false,
              delete: false,
            };
            break;

          case "roles":
            permissions = {
              read: true,
              create: false,
              edit: false,
              delete: false,
            };
            break;

          case "libraries":
            permissions = {
              read: true,
              create: true,
              edit: true,
              delete: false,
              export: true,
              share: true,
            };
            break;

          default:
            // ❌ no permission for other modules
            permissions = {};
            break;
        }

        // skip if no permissions
        if (!Object.keys(permissions).length) return null;

        return {
          moduleId: module._id,
          moduleName: module.name,
          permissions,
        };
      })
      .filter(Boolean);

    const updated = await Role.findByIdAndUpdate(
      ROLE_ID,
      { $set: { modulePermissions } },
      { new: true }
    );

    console.log("✅ Updated Role:", updated?.name, updated?._id);
    console.log("✅ Modules Permission Count:", modulePermissions.length);

    process.exit(0);
  } catch (error) {
    console.error("❌ Seeder Error:", error);
    process.exit(1);
  }
};

seedRolePermission();