/**
 * Routes Opportunity trigger records to the Close-Won validation service.
 */
public with sharing class OpportunityContactRoleCloseWonHandler {
    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.';

    /**
     * Applies the Close-Won rule only to UI-session edits. API and system
     * integration transactions are excluded.
     */
    public static void run() {
        if (!isUiEdit()) {
            return;
        }

        List<Opportunity> opportunities = (List<Opportunity>) Trigger.new;
        Map<Id, Opportunity> oldOpportunities = Trigger.isUpdate
            ? (Map<Id, Opportunity>) Trigger.oldMap
            : new Map<Id, Opportunity>();

        for (Opportunity opportunity : CloseWonService.getOpportunitiesWithoutRoles(
            opportunities,
            oldOpportunities,
            Trigger.isUpdate
        )) {
            opportunity.addError(VALIDATION_MESSAGE);
        }
    }

    @TestVisible
    private static Boolean isUiEdit() {
        String userType = UserInfo.getUserType();
        if (userType == 'AutomatedProcess' || userType == 'CloudIntegrationUser') {
            return false;
        }

        Map<String, String> sessionDetails = Auth.SessionManagement.getCurrentSession();
        return sessionDetails != null && sessionDetails.get('SessionType') == 'UI';
    }

    /**
     * Encapsulates the Close-Won business rule and its Contact Role query.
     */
    @TestVisible
    private class CloseWonService {
        private static final String CLOSED_WON_STAGE = 'Closed Won';

        /**
         * Returns trigger records entering Closed Won that have no Contact Role.
         *
         * @param opportunities Current trigger records.
         * @param oldOpportunities Previous trigger records, when updating.
         * @param isUpdate Whether the trigger is processing updates.
         * @return Opportunities that must be blocked.
         */
        private static List<Opportunity> getOpportunitiesWithoutRoles(
            List<Opportunity> opportunities,
            Map<Id, Opportunity> oldOpportunities,
            Boolean isUpdate
        ) {
            Map<Id, Opportunity> candidatesById = new Map<Id, Opportunity>();
            List<Opportunity> candidatesWithoutId = new List<Opportunity>();

            for (Opportunity opportunity : opportunities) {
                if (opportunity.StageName != CLOSED_WON_STAGE) {
                    continue;
                }
                if (isUpdate
                    && oldOpportunities.get(opportunity.Id).StageName == CLOSED_WON_STAGE) {
                    continue;
                }

                if (opportunity.Id == null) {
                    candidatesWithoutId.add(opportunity);
                } else {
                    candidatesById.put(opportunity.Id, opportunity);
                }
            }

            Set<Id> opportunityIds = candidatesById.keySet();
            Set<Id> opportunitiesWithRoles = new Set<Id>();
            if (!opportunityIds.isEmpty()) {
                for (OpportunityContactRole contactRole : [
                    SELECT OpportunityId
                    FROM OpportunityContactRole
                    WHERE OpportunityId IN :opportunityIds
                    WITH USER_MODE
                ]) {
                    opportunitiesWithRoles.add(contactRole.OpportunityId);
                }
            }

            List<Opportunity> opportunitiesWithoutRoles = candidatesWithoutId;
            for (Id opportunityId : candidatesById.keySet()) {
                if (!opportunitiesWithRoles.contains(opportunityId)) {
                    opportunitiesWithoutRoles.add(candidatesById.get(opportunityId));
                }
            }
            return opportunitiesWithoutRoles;
        }
    }
}
