BEGIN;

-- users / master tables
ALTER TABLE users ALTER COLUMN status TYPE VARCHAR(16) USING status::text;
ALTER TABLE companies ALTER COLUMN status TYPE VARCHAR(16) USING status::text;
ALTER TABLE sites ALTER COLUMN status TYPE VARCHAR(16) USING status::text;
ALTER TABLE systems ALTER COLUMN status TYPE VARCHAR(16) USING status::text;
ALTER TABLE modules ALTER COLUMN status TYPE VARCHAR(16) USING status::text;
ALTER TABLE permission_groups ALTER COLUMN status TYPE VARCHAR(16) USING status::text;

-- api_clients
ALTER TABLE api_clients ALTER COLUMN status TYPE VARCHAR(16) USING status::text;

-- user scoped permissions
ALTER TABLE user_scope_permissions ALTER COLUMN action TYPE VARCHAR(32) USING action::text;
ALTER TABLE user_scope_permissions ALTER COLUMN scope_type TYPE VARCHAR(16) USING scope_type::text;

-- keep check constraint compatible with varchar
ALTER TABLE user_scope_permissions DROP CONSTRAINT IF EXISTS user_scope_permissions_check;
ALTER TABLE user_scope_permissions
  ADD CONSTRAINT user_scope_permissions_check
  CHECK (
    ((scope_type = 'company' AND company_id IS NOT NULL AND site_id IS NULL)
     OR (scope_type = 'site' AND site_id IS NOT NULL AND company_id IS NULL))
  );

COMMIT;
