-- 20260420000002_cleanup_role_tables.up.sql (the rename half relevant here)
-- was disabled as .up.sql.skip, so role_permissions/dashboard_configs/
-- runtime_configs/user_roles never get renamed to the names the live app
-- code (config.rs, external_roles.rs, user_roles.rs, ...) actually queries:
-- role_admin_permissions/role_sidebar_configs/role_runtime_configs/
-- user_role_assignments. 20260422000000_seed_widgets needs
-- role_sidebar_configs to exist, so any fresh bootstrap fails there.
--
-- Unlike the external-role-module tables migration, this can't just be
-- "IF NOT EXISTS" -- a RENAME's source table stops existing once it's
-- done, so re-running it errors on an environment where it already
-- happened (including this repo's own production, per the skip file's own
-- history). Each rename below only fires if the old name still exists and
-- the new name doesn't yet -- safe to run on any environment regardless of
-- which (if any) of these renames it already has.
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'role_permissions')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'role_admin_permissions') THEN
        ALTER TABLE role_permissions RENAME TO role_admin_permissions;
    END IF;

    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'dashboard_configs')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'role_sidebar_configs') THEN
        ALTER TABLE dashboard_configs RENAME TO role_sidebar_configs;
    END IF;

    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'runtime_configs')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'role_runtime_configs') THEN
        ALTER TABLE runtime_configs RENAME TO role_runtime_configs;
    END IF;

    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'user_roles')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'user_role_assignments') THEN
        ALTER TABLE user_roles RENAME TO user_role_assignments;
    END IF;
END $$;
