/**
 * Tests the Contact Role requirement for Opportunities entering Closed Won.
 */
@isTest
private with sharing class OpportunityContactRoleCloseWonHandlerTest {
    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.';

    /**
     * Verifies the bulk rule and, when running in a UI session, the trigger errors.
     */
    @isTest
    static void testBulkCloseWonRequiresContactRole() {
        Account account = new Account(Name = 'Close Won Guard Test Account');
        Database.insert(account, AccessLevel.USER_MODE);

        List<Opportunity> opportunities = new List<Opportunity>();
        String openStage = getOpenStageName();
        for (Integer index = 0; index < 200; index++) {
            opportunities.add(new Opportunity(
                Name = 'Close Won Guard Test ' + index,
                AccountId = account.Id,
                StageName = openStage,
                CloseDate = Date.today().addDays(30)
            ));
        }
        Database.insert(opportunities, AccessLevel.USER_MODE);

        Contact contact = new Contact(
            FirstName = 'Contact Role',
            LastName = 'Test',
            AccountId = account.Id
        );
        Database.insert(contact, AccessLevel.USER_MODE);
        OpportunityContactRole contactRole = new OpportunityContactRole(
            OpportunityId = opportunities[0].Id,
            ContactId = contact.Id,
            IsPrimary = true
        );
        Database.insert(contactRole, AccessLevel.USER_MODE);

        Map<Id, Opportunity> oldOpportunities = new Map<Id, Opportunity>();
        for (Opportunity opportunity : opportunities) {
            oldOpportunities.put(opportunity.Id, new Opportunity(
                Id = opportunity.Id,
                StageName = openStage
            ));
            opportunity.StageName = CLOSED_WON_STAGE;
        }

        Test.startTest();
        List<Opportunity> invalidOpportunities =
            OpportunityContactRoleCloseWonHandler.CloseWonService.getOpportunitiesWithoutRoles(
                opportunities,
                oldOpportunities,
                true
            );
        Test.stopTest();

        System.assertEquals(
            199,
            invalidOpportunities.size(),
            'Every Closed Won Opportunity without a Contact Role should be identified.'
        );
        System.assertEquals(
            opportunities[1].Id,
            invalidOpportunities[0].Id,
            'The first Opportunity without a Contact Role should be identified.'
        );

        // Apex tests may not have a UI session. The service assertions above cover
        // the business rule in that context; verify addError behavior when available.
        if (!OpportunityContactRoleCloseWonHandler.isUiEdit()) {
            return;
        }

        Database.SaveResult[] results = Database.update(
            opportunities,
            false,
            AccessLevel.USER_MODE
        );
        System.assertEquals(200, results.size(), 'All 200 updates should return a result.');
        System.assert(results[0].isSuccess(), 'The Opportunity with a Contact Role should save.');
        for (Integer index = 1; index < results.size(); index++) {
            System.assert(!results[index].isSuccess(), 'An Opportunity without a Contact Role must fail.');
            System.assertEquals(
                VALIDATION_MESSAGE,
                results[index].getErrors()[0].getMessage(),
                'The validation error should match the required message.'
            );
        }
    }

    private static String getOpenStageName() {
        for (Schema.PicklistEntry stage : Opportunity.StageName.getDescribe().getPicklistValues()) {
            if (stage.isActive() && stage.getValue() != CLOSED_WON_STAGE) {
                return stage.getValue();
            }
        }
        System.assert(false, 'An active open Opportunity stage is required for this test.');
        return null;
    }
}
