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

    await queryInterface.sequelize.query(`
      CREATE TABLE IF NOT EXISTS "rolesPermissionsPermissions"
      (
        "createdAt" timestamp with time zone not null,
        "updatedAt" timestamp with time zone not null,
        "roles_permissionsId" uuid not null,
        "permissionId" uuid not null,
        primary key ("roles_permissionsId", "permissionId")
      );
    `);

    // Find all roles
    const roles = await queryInterface.sequelize.query(
      `SELECT id, name FROM roles WHERE name != 'Public';`,
      { type: Sequelize.QueryTypes.SELECT }
    );
    // Find the read permission
    const permissions = await queryInterface.sequelize.query(
      `SELECT id, name FROM permissions WHERE name = 'READ_WORKERS_COMP_CLASSES';`,
      { 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) => {}
};
