DO $$
DECLARE
  v_count int;
BEGIN
  SELECT count(*) INTO v_count
  FROM users
  WHERE phone_number = '8939910100';

  IF v_count = 0 THEN
    RAISE EXCEPTION 'vijjisubbu not found for phone_number = %', '8939910100';
  ELSIF v_count > 1 THEN
    RAISE EXCEPTION 'phone_number % matched % users - refusing to proceed', '8939910100', v_count;
  END IF;
END $$;


INSERT INTO user_role_map (user_id, role_id)
SELECT u.id, (SELECT id FROM user_role WHERE role_key = 'ROLE_SHOBA')
FROM users u
WHERE u.phone_number = '8939910100'
  AND NOT EXISTS (
    SELECT 1 FROM user_role_map urm
    WHERE urm.user_id = u.id
      AND urm.role_id = (SELECT id FROM user_role WHERE role_key = 'ROLE_SHOBA')
  );

SELECT u.id, u.full_name, r.role_key, r.name AS role_name
FROM users u
JOIN user_role_map urm ON urm.user_id = u.id
JOIN user_role r        ON r.id = urm.role_id
WHERE u.phone_number = '8939910100'
ORDER BY r.role_key;

SELECT id, phone_number, full_name, org_usr_name
FROM users
WHERE phone_number = '8939910100';

UPDATE users
SET org_usr_name = 'other'
WHERE phone_number = '8939910100';
