BEGIN;

DO $$
BEGIN
  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'users' AND column_name = 'idp_sub'
  ) AND NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'users' AND column_name = 'user_sub'
  ) THEN
    ALTER TABLE users RENAME COLUMN idp_sub TO user_sub;
  END IF;

  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'users' AND column_name = 'idp_user_id'
  ) AND NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'users' AND column_name = 'idp_user_id'
  ) THEN
    ALTER TABLE users RENAME COLUMN idp_user_id TO idp_user_id;
  END IF;

  IF EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'permission_group_members' AND column_name = 'idp_sub'
  ) AND NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'permission_group_members' AND column_name = 'user_sub'
  ) THEN
    ALTER TABLE permission_group_members RENAME COLUMN idp_sub TO user_sub;
  END IF;
END
$$;

ALTER INDEX IF EXISTS idx_users_idp_sub RENAME TO idx_users_user_sub;
ALTER INDEX IF EXISTS idx_pgm_idp_sub RENAME TO idx_pgm_user_sub;

CREATE INDEX IF NOT EXISTS idx_users_user_sub ON users(user_sub);
CREATE INDEX IF NOT EXISTS idx_pgm_user_sub ON permission_group_members(user_sub);

COMMIT;
