module.exports = {
  async up(queryInterface, Sequelize) {
    const [[publicRole]] = await queryInterface.sequelize.query(
      "SELECT id FROM roles WHERE name = 'Public' LIMIT 1"
    );

    if (!publicRole) return;

    const [permissions] = await queryInterface.sequelize.query(
      "SELECT id FROM permissions WHERE name IN ('CREATE_SEARCH', 'CREATE_BUSINESSES')"
    );

    if (!permissions.length) return;

    // Avoid duplicate inserts
    for (const permission of permissions) {
        const [[existing]] = await queryInterface.sequelize.query(
            `SELECT * FROM "rolesPermissionsPermissions" WHERE "roles_permissionsId" = '${publicRole.id}' AND "permissionId" = '${permission.id}'`
        );
        if (!existing) {
            await queryInterface.sequelize.query(
                `INSERT INTO "rolesPermissionsPermissions" ("roles_permissionsId", "permissionId", "createdAt", "updatedAt") VALUES ('${publicRole.id}', '${permission.id}', NOW(), NOW())`
            );
        }
    }
  },

  async down(queryInterface, Sequelize) {
  },
};