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

module.exports = {
  async up(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      const entities = ['PROJECTS'];
      const actions = ['CREATE', 'READ', 'UPDATE', 'DELETE'];
      const timestamp = new Date();

      // 1. Insert Permissions
      const newPermissions = [];
      for (const entity of entities) {
        for (const action of actions) {
          newPermissions.push({
            id: uuid(),
            name: `${action}_${entity}`,
            createdAt: timestamp,
            updatedAt: timestamp,
          });
        }
      }

      await queryInterface.bulkInsert('permissions', newPermissions, { transaction });

      // 2. Get Roles
      const [roles] = await queryInterface.sequelize.query(
        "SELECT id, name FROM roles WHERE name IN ('Administrator', 'Super Administrator')",
        { transaction }
      );

      // 3. Link Permissions to Roles
      const rolePermissions = [];
      for (const role of roles) {
        for (const perm of newPermissions) {
          rolePermissions.push({
            roles_permissionsId: role.id,
            permissionId: perm.id,
            createdAt: timestamp,
            updatedAt: timestamp,
          });
        }
      }

      if (rolePermissions.length > 0) {
        await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions, { transaction });
      }

      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },

  async down(queryInterface, Sequelize) {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      // Find permissions to delete
      const [permissions] = await queryInterface.sequelize.query(
        "SELECT id FROM permissions WHERE name LIKE '%_PROJECTS'",
        { transaction }
      );

      const permissionIds = permissions.map(p => p.id);

      if (permissionIds.length > 0) {
        // Delete from join table
        await queryInterface.bulkDelete(
          'rolesPermissionsPermissions',
          { permissionId: { [Sequelize.Op.in]: permissionIds } },
          { transaction }
        );

        // Delete from permissions table
        await queryInterface.bulkDelete(
          'permissions',
          { id: { [Sequelize.Op.in]: permissionIds } },
          { transaction }
        );
      }

      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },
};
