@isTest
private with sharing class OpportunityContactRoleGuardTest {
    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.';

    @isTest
    static void rejectsClosedWonWithoutContactRole() {
        Contact contact = createContact();
        Opportunity opportunity = createOpportunity('Prospecting');

        Test.startTest();
        opportunity.StageName = 'Closed Won';
        Database.SaveResult result = Database.update(opportunity, false);
        Test.stopTest();

        System.assertEquals(false, result.isSuccess(), 'Closed Won must be rejected without a Contact Role.');
        System.assertEquals(VALIDATION_MESSAGE, result.getErrors()[0].getMessage(), 'The required validation message must be shown.');
        System.assertNotEquals(null, contact.Id, 'Test contact was created.');
    }

    @isTest
    static void allowsClosedWonWithContactRole() {
        Contact contact = createContact();
        Opportunity opportunity = createOpportunity('Prospecting');
        insert new OpportunityContactRole(
            OpportunityId = opportunity.Id,
            ContactId = contact.Id,
            Role = 'Decision Maker',
            IsPrimary = true
        );

        Test.startTest();
        opportunity.StageName = 'Closed Won';
        update opportunity;
        Test.stopTest();

        System.assertEquals('Closed Won', [
            SELECT StageName
            FROM Opportunity
            WHERE Id = :opportunity.Id
            WITH USER_MODE
        ].StageName, 'An Opportunity with a Contact Role may be closed won.');
    }

    @isTest
    static void handlesBulkClosedWonUpdates() {
        Contact contact = createContact();
        List<Opportunity> opportunities = new List<Opportunity>();
        for (Integer indexValue = 0; indexValue < 200; indexValue++) {
            opportunities.add(new Opportunity(
                Name = 'Bulk Opportunity ' + indexValue,
                AccountId = contact.AccountId,
                CloseDate = Date.today().addDays(30),
                StageName = 'Prospecting'
            ));
        }
        insert opportunities;

        List<OpportunityContactRole> contactRoles = new List<OpportunityContactRole>();
        for (Opportunity opportunity : opportunities) {
            contactRoles.add(new OpportunityContactRole(
                OpportunityId = opportunity.Id,
                ContactId = contact.Id,
                Role = 'Decision Maker',
                IsPrimary = true
            ));
            opportunity.StageName = 'Closed Won';
        }
        insert contactRoles;

        Test.startTest();
        update opportunities;
        Test.stopTest();

        System.assertEquals(200, [
            SELECT COUNT()
            FROM Opportunity
            WHERE Id IN :opportunities AND StageName = 'Closed Won'
            WITH USER_MODE
        ], 'All qualifying records in a bulk update should be allowed.');
    }

    private static Contact createContact() {
        Account account = new Account(Name = 'Guard Test Account');
        insert account;
        Contact contact = new Contact(LastName = 'Guard Test Contact', AccountId = account.Id);
        insert contact;
        return contact;
    }

    private static Opportunity createOpportunity(String stageName) {
        Contact contact = createContact();
        Opportunity opportunity = new Opportunity(
            Name = 'Guard Test Opportunity',
            AccountId = contact.AccountId,
            CloseDate = Date.today().addDays(30),
            StageName = stageName
        );
        insert opportunity;
        return opportunity;
    }
}
