/**
 * Delegates Opportunity Closed Won Contact Role validation to its service.
 * The rule enforces the business requirement for interactive users and excludes
 * automated processing and users assigned the Salesforce Integration license.
 */
public with sharing class OpportunityContactRoleGuardHandler {
    /**
     * Validates trigger records before they are saved.
     *
     * @param newRecords Trigger.new records.
     * @param oldMap Trigger.oldMap, or null during insert.
     */
    public static void run(List<Opportunity> newRecords, Map<Id, Opportunity> oldMap) {
        OpportunityContactRoleGuardService service = new OpportunityContactRoleGuardService();
        service.validate(newRecords, oldMap);
    }

    private class OpportunityContactRoleGuardService {
        private static final String CLOSED_WON_STAGE = 'Closed Won';
        private static final String VALIDATION_MESSAGE = 'Validation Error: You cannot close-win this Opportunity without assigning at least one Contact Role. Please add a contact to the Opportunity Contact Roles related list and try again.';
        private final OpportunityContactRoleSelector selector = new OpportunityContactRoleSelector();

        private void validate(List<Opportunity> newRecords, Map<Id, Opportunity> oldMap) {
            if (selector.isExcludedIntegrationContext()) {
                return;
            }

            Set<Id> opportunityIdsToCheck = new Set<Id>();
            List<Opportunity> recordsWithoutIds = new List<Opportunity>();

            for (Opportunity opportunity : newRecords) {
                if (opportunity.StageName != CLOSED_WON_STAGE) {
                    continue;
                }

                if (oldMap != null) {
                    Opportunity oldOpportunity = oldMap.get(opportunity.Id);
                    if (oldOpportunity == null || oldOpportunity.StageName == CLOSED_WON_STAGE) {
                        continue;
                    }
                }

                if (opportunity.Id == null) {
                    recordsWithoutIds.add(opportunity);
                } else {
                    opportunityIdsToCheck.add(opportunity.Id);
                }
            }

            for (Opportunity opportunity : recordsWithoutIds) {
                opportunity.addError(VALIDATION_MESSAGE);
            }

            if (opportunityIdsToCheck.isEmpty()) {
                return;
            }

            Set<Id> opportunityIdsWithContactRoles = selector.getOpportunityIdsWithContactRoles(opportunityIdsToCheck);
            for (Opportunity opportunity : newRecords) {
                if (opportunityIdsToCheck.contains(opportunity.Id)
                    && !opportunityIdsWithContactRoles.contains(opportunity.Id)) {
                    opportunity.addError(VALIDATION_MESSAGE);
                }
            }
        }
    }

    private with sharing class OpportunityContactRoleSelector {
        private static final String SALESFORCE_INTEGRATION_LICENSE = 'Salesforce Integration';

        private Set<Id> getOpportunityIdsWithContactRoles(Set<Id> opportunityIds) {
            Set<Id> opportunityIdsWithContactRoles = new Set<Id>();

            // This existence check enforces an approved business invariant, not user-facing data access.
            // System mode is necessary so record sharing or CRUD/FLS cannot hide an associated role
            // and allow an invalid Closed Won update. Only the related OpportunityId is retrieved.
            for (OpportunityContactRole contactRole : [
                SELECT OpportunityId
                FROM OpportunityContactRole
                WHERE OpportunityId IN :opportunityIds
                WITH SYSTEM_MODE
            ]) {
                opportunityIdsWithContactRoles.add(contactRole.OpportunityId);
            }
            return opportunityIdsWithContactRoles;
        }

        private Boolean isExcludedIntegrationContext() {
            if (UserInfo.getUserType() == 'AutomatedProcess') {
                return true;
            }

            // Salesforce Integration is the platform license criterion for these integration users;
            // resolve it from the running user's profile rather than relying on user IDs or names.
            List<Profile> runningProfile = [
                SELECT UserLicense.Name
                FROM Profile
                WHERE Id = :UserInfo.getProfileId()
                WITH SYSTEM_MODE
                LIMIT 1
            ];
            return !runningProfile.isEmpty()
                && runningProfile[0].UserLicense.Name == SALESFORCE_INTEGRATION_LICENSE;
        }
    }
}
