public without sharing class OpportunityDataMigration {
    public static void run() {
        // Query all open Opportunities
        List<Opportunity> opps = [SELECT Id, Amount, AccountId, Type, StageName, Deal_Size_Tier__c FROM Opportunity WHERE IsClosed = false];
        // Get thresholds from custom metadata (assume Deal_Size_Tier__mdt with fields Min_Amount__c, Tier__c)
        Map<String, Decimal> tierThresholds = new Map<String, Decimal>();
        for (Deal_Size_Tier__mdt tier : [SELECT Tier__c, Min_Amount__c FROM Deal_Size_Tier__mdt]) {
            tierThresholds.put(tier.Tier__c, tier.Min_Amount__c);
        }
        // Sort tiers by Min_Amount__c descending
        List<String> sortedTiers = new List<String>(tierThresholds.keySet());
        sortedTiers.sort((a, b) => tierThresholds.get(b).compareTo(tierThresholds.get(a)));
        List<Opportunity> updates = new List<Opportunity>();
        for (Opportunity opp : opps) {
            // Assign Deal Size Tier
            String newTier = null;
            for (String tier : sortedTiers) {
                if (opp.Amount != null && opp.Amount >= tierThresholds.get(tier)) {
                    newTier = tier;
                    break;
                }
            }
            if (newTier == null) newTier = 'Small';
            if (opp.Deal_Size_Tier__c != newTier) {
                opp.Deal_Size_Tier__c = newTier;
            }
            // Assign Type (stub: set to 'New Business' if Account has no closed-won Opps, else 'Renewal')
            if (opp.Type == null) {
                Integer wonCount = [SELECT COUNT() FROM Opportunity WHERE AccountId = :opp.AccountId AND IsClosed = true AND IsWon = true];
                opp.Type = (wonCount == 0) ? 'New Business' : 'Renewal';
            }
            updates.add(opp);
        }
        if (!updates.isEmpty()) {
            update updates;
        }
    }
}
