const { v4: uuid } = require("uuid");

module.exports = {
  /**
   * @param{import("sequelize").QueryInterface} queryInterface
   * @return {Promise<void>}
   */
  async up(queryInterface) {
    const createdAt = new Date();
    const updatedAt = new Date();

    /** @type {Map<string, string>} */
    const idMap = new Map();

    /**
     * @param {string} key
     * @return {string}
     */
    function getId(key) {
      if (idMap.has(key)) {
        return idMap.get(key);
      }
      const id = uuid();
      idMap.set(key, id);
      return id;
    }

    // Since we are updating, we should try to fetch existing IDs if possible, 
    // but in a seeder for this kind of platform it's often better to just recreate or use fixed IDs if they were fixed.
    // However, the previous seeder used random UUIDs. 
    // To update permissions, I'll need to fetch the roles.

    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM "roles";`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const permissions = await queryInterface.sequelize.query(
      `SELECT id, name FROM "permissions";`,
      { type: queryInterface.sequelize.QueryTypes.SELECT }
    );

    const getRoleId = (name) => roles.find(r => r.name === name)?.id;
    const getPermId = (name) => permissions.find(p => p.name === name)?.id;

    const vboRoleId = getRoleId("Verified Business Owner");

    if (vboRoleId) {
      const newPerms = [
        "CREATE_BUSINESSES",
        "UPDATE_REVIEWS",
        "CREATE_BUSINESS_PHOTOS",
        "CREATE_BUSINESS_CATEGORIES",
        "CREATE_SERVICE_PRICES",
        "CREATE_LEAD_MATCHES", // Maybe?
        "CREATE_MESSAGES",
      ];

      const rolePermsToInsert = [];
      for (const p of newPerms) {
        const permId = getPermId(p);
        if (permId) {
          // Check if it already exists
          const existing = await queryInterface.sequelize.query(
            `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${vboRoleId}' AND "permissionId" = '${permId}';`,
            { type: queryInterface.sequelize.QueryTypes.SELECT }
          );
          if (existing.length === 0) {
            rolePermsToInsert.push({
              createdAt,
              updatedAt,
              roles_permissionsId: vboRoleId,
              permissionId: permId
            });
          }
        }
      }

      if (rolePermsToInsert.length > 0) {
        await queryInterface.bulkInsert("rolesPermissionsPermissions", rolePermsToInsert);
      }
    }
  },

  async down(queryInterface) {
    // No easy way to undo this without more logic
  }
};