'use strict';
module.exports = {
  up: async (queryInterface, Sequelize) => {
    const createdAt = new Date();
    const updatedAt = new Date();
    
    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM roles WHERE name != 'Public';`,
      { type: Sequelize.QueryTypes.SELECT }
    );
    
    const permissions = await queryInterface.sequelize.query(
      `SELECT id, name FROM permissions WHERE name = 'READ_EMPLOYEE_PAY_TYPES';`,
      { type: Sequelize.QueryTypes.SELECT }
    );
    
    if (permissions.length === 0) return;
    const readPerm = permissions[0];
    const rolePermissions = [];
    
    const existing = await queryInterface.sequelize.query(
      `SELECT "roles_permissionsId", "permissionId" FROM "rolesPermissionsPermissions" WHERE "permissionId" = '${readPerm.id}';`,
      { type: Sequelize.QueryTypes.SELECT }
    );
    const existingSet = new Set(existing.map(e => e.roles_permissionsId + '-' + e.permissionId));
    
    for (const role of roles) {
        if (!existingSet.has(role.id + '-' + readPerm.id)) {
            rolePermissions.push({
                roles_permissionsId: role.id,
                permissionId: readPerm.id,
                createdAt,
                updatedAt,
            });
        }
    }
    if (rolePermissions.length > 0) {
      await queryInterface.bulkInsert('rolesPermissionsPermissions', rolePermissions);
    }
  },
  down: async (queryInterface, Sequelize) => {}
};
