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

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const createdAt = new Date();
    const updatedAt = new Date();
    const entity = 'workers_comp_classes';

    const permissions = [
      { id: uuid(), name: `CREATE_${entity.toUpperCase()}`, createdAt, updatedAt },
      { id: uuid(), name: `READ_${entity.toUpperCase()}`, createdAt, updatedAt },
      { id: uuid(), name: `UPDATE_${entity.toUpperCase()}`, createdAt, updatedAt },
      { id: uuid(), name: `DELETE_${entity.toUpperCase()}`, createdAt, updatedAt },
    ];

    await queryInterface.bulkInsert('permissions', permissions);

    // Get Admin and SystemOwner roles
    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM roles WHERE name IN ('Administrator', 'SystemOwner');`,
      { type: Sequelize.QueryTypes.SELECT }
    );

    const rolePermissions = [];
    for (const role of roles) {
      for (const perm of permissions) {
        rolePermissions.push({
          roles_permissionsId: role.id,
          permissionId: perm.id,
          createdAt,
          updatedAt,
        });
      }
    }

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

  down: async (queryInterface, Sequelize) => {
    const entity = 'workers_comp_classes';
    const permissionNames = [
      `CREATE_${entity.toUpperCase()}`,
      `READ_${entity.toUpperCase()}`,
      `UPDATE_${entity.toUpperCase()}`,
      `DELETE_${entity.toUpperCase()}`,
    ];

    await queryInterface.sequelize.query(
      `DELETE FROM "rolesPermissionsPermissions" WHERE "permissionId" IN (SELECT id FROM permissions WHERE name IN (:names));`,
      { replacements: { names: permissionNames } }
    );

    await queryInterface.bulkDelete('permissions', {
      name: {
        [Sequelize.Op.in]: permissionNames,
      },
    });
  },
};
