<?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: Max Daily Hours</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;
    }

    const MAX_DAILY_MS = 12 * 60 * 60 * 1000;

    // Collect all of this contact's shift intervals, starting with the shift being evaluated
    const intervals = [[currentStart, currentEnd]];

    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) || loadedStart >= loadedEnd) {
            continue;
        }

        intervals.push([loadedStart, loadedEnd]);
    }

    // local (browser) calendar days — swap to app-timezone midnights if clients cross timezones
    const localMidnight = (ms) => {
        const d = new Date(ms);
        return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
    };

    let violationFound = false;

    // Walk each calendar day the evaluated shift touches and total the contact's scheduled time on it
    for (let dayStart = localMidnight(currentStart); dayStart < currentEnd; dayStart = localMidnight(dayStart + 26 * 60 * 60 * 1000)) {
        const dayEnd = localMidnight(dayStart + 26 * 60 * 60 * 1000);

        let scheduledMs = 0;
        for (const [start, end] of intervals) {
            const overlap = Math.min(end, dayEnd) - Math.max(start, dayStart);
            if (overlap > 0) {
                scheduledMs += overlap;
            }
        }

        if (scheduledMs > MAX_DAILY_MS) {
            violationFound = true;
            const hoursScheduled = (scheduledMs / (1000 * 60 * 60)).toFixed(1);
            const dayLabel = new Date(dayStart).toLocaleDateString();

            results.push(
                new EvaluationResult({
                    event: event,
                    detail: `⚠️ Over Daily Limit: ${hoursScheduled} hrs scheduled on ${dayLabel} (Max: 12 hrs)`,
                    category: 'Daily Hours Compliance',
                    points: -100,
                    maxPoints: 15,
                    isBlocking: false,
                    isEliminating: false
                })
            );
        }
    }

    if (!violationFound) {
        results.push(
            new EvaluationResult({
                event: event,
                detail: `👍 Compliant: Worker is scheduled 12 hours or less on every day this shift touches`,
                category: 'Daily Hours 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>
