<?xml version="1.0" encoding="UTF-8"?>
<CustomMetadata xmlns="http://soap.sforce.com/2006/04/metadata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <label>Scheduler: Breaks</label>
    <protected>false</protected>
    <values>
        <field>b3s__Configuration__c</field>
        <value xsi:type="xsd:string"><![CDATA[
        
        ]]></value>
    </values>
    <values>
        <field>b3s__Javascript_Code__c</field>
        <value xsi:type="xsd:string"><![CDATA[
async ({ event, events, contactId, loaders, matchingModifiers, EvaluationResult }) => {
    let results = [];
    if (!contactId) {
        console.warn('No contact id for evaluation');
        return results;
    }

    const currentStart = new Date(event.start).getTime();
    const currentEnd = new Date(event.end).getTime();

    // Guard clause: ensure valid date ranges on contextual event
    if (isNaN(currentStart) || isNaN(currentEnd) || currentStart >= currentEnd) {
        return results;
    }

    // Art. 34.3 Estatuto de los Trabajadores: minimum 12h rest between the end of one
    // workday (jornada) and the start of the next. Shifts on the SAME calendar day are
    // split shifts (jornada partida) — exempt here, capped by the Max Daily Hours rule.
    const REQUIRED_BREAK_MS = 12 * 60 * 60 * 1000;
    let breakViolationFound = false;

    // local (browser) calendar days — same convention as Max Daily Hours rule
    const sameLocalDay = (msA, msB) => {
        const a = new Date(msA);
        const b = new Date(msB);
        return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
    };

    // Loop through all other cache-loaded events to evaluate rest period gaps
    for (const loadedEvent of events) {
        // Skip comparing the event against itself
        if (loadedEvent.id === event.id) {
            continue;
        }

        // Only check verified 'shift' types
        if (!loadedEvent.title || loadedEvent.title.toLowerCase() !== 'shift') {
            continue;
        }

        // Verify the loaded shift belongs to the same contact being evaluated
        const loadedEventContactId = loadedEvent.extendedProps?.record?.b3s__Contact__c; 
        if (!loadedEventContactId || loadedEventContactId !== contactId) {
            continue;
        }

        const loadedStart = new Date(loadedEvent.start).getTime();
        const loadedEnd = new Date(loadedEvent.end).getTime();

        if (isNaN(loadedStart) || isNaN(loadedEnd)) {
            continue;
        }

        // Check for two separate conditions based on relative scheduling chronological ordering:
        // Case A: Loaded shift ends AFTER the current shift starts, but BEFORE it ends (overlapping logic handled separately, but rest rules apply)
        // Case B: Loaded shift happens BEFORE the current shift
        if (loadedEnd <= currentStart) {
            // Same calendar day = split shift (jornada partida) — no 12h rule between them
            if (sameLocalDay(loadedEnd, currentStart)) {
                continue;
            }
            const actualBreak = currentStart - loadedEnd;
            if (actualBreak < REQUIRED_BREAK_MS) {
                breakViolationFound = true;
                const hoursBreak = (actualBreak / (1000 * 60 * 60)).toFixed(1);
                const shiftName = loadedEvent.extendedProps?.record?.Name || 'Prior Shift';

                results.push(
                    new EvaluationResult({
                        event: event,
                        detail: `⚠️ Insufficient Rest: Only ${hoursBreak} hrs of rest after "${shiftName}" (Required: 12 hrs between workdays)`,
                        category: 'Rest Period Compliance',
                        points: -100,
                        maxPoints: 15,
                        isBlocking: false,
                        isEliminating: false
                    })
                );
            }
        }
        // Case C: Loaded shift happens AFTER the current shift
        else if (loadedStart >= currentEnd) {
            // Same calendar day = split shift (jornada partida) — no 12h rule between them
            if (sameLocalDay(currentEnd, loadedStart)) {
                continue;
            }
            const actualBreak = loadedStart - currentEnd;
            if (actualBreak < REQUIRED_BREAK_MS) {
                breakViolationFound = true;
                const hoursBreak = (actualBreak / (1000 * 60 * 60)).toFixed(1);
                const shiftName = loadedEvent.extendedProps?.record?.Name || 'Subsequent Shift';

                results.push(
                    new EvaluationResult({
                        event: event,
                        detail: `⚠️ Insufficient Rest: Only ${hoursBreak} hrs of rest before "${shiftName}" (Required: 12 hrs between workdays)`,
                        category: 'Rest Period Compliance',
                        points: -100,
                        maxPoints: 15,
                        isBlocking: false,
                        isEliminating: false
                    })
                );
            }
        }
    }

    // If no rest break guidelines were violated, award positive scoring points
    if (!breakViolationFound) {
        results.push(
            new EvaluationResult({
                event: event,
                detail: `👍 Compliant: Worker has at least 12 hours of rest between this shift and adjacent workdays`,
                category: 'Rest Period Compliance',
                points: 15,
                maxPoints: 15,
                isBlocking: false
            })
        );
    }

    return results;
}

        ]]></value>
    </values>
    <values>
        <field>b3s__Type__c</field>
        <value xsi:type="xsd:string">Scheduling</value>
    </values>
</CustomMetadata>
