"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mergeWorkflowSetupOptions = mergeWorkflowSetupOptions;
const command_apply_1 = require("./command-apply");
function mergeWorkflowSetupOptions(input) {
    const merged = {};
    applyWorkflowOptionDefaults(merged, input.autofill);
    applyWorkflowOptionDefaults(merged, input.selection);
    applyWorkflowOptionOverrides(merged, input.explicit);
    return Object.keys(merged).length === 0 ? null : merged;
}
const WORKFLOW_OPTION_KEYS = [
    "workflowSelection",
    "workflowTemplateSelectors",
    "schedule",
    "scheduledRun",
    "firstRun",
    "recurringAutoStop",
    "baseBranch",
    "configOverridePatch",
];
function applyWorkflowOptionDefaults(target, source) {
    if (source === null || source === undefined) {
        return;
    }
    for (const key of WORKFLOW_OPTION_KEYS) {
        if (key === "configOverridePatch") {
            applyConfigOverridePatchDefaults(target, source.configOverridePatch);
            continue;
        }
        if (target[key] !== undefined || source[key] === undefined) {
            continue;
        }
        assignWorkflowOptionField(target, key, source[key]);
    }
}
function applyWorkflowOptionOverrides(target, source) {
    if (source === null || source === undefined) {
        return;
    }
    for (const key of WORKFLOW_OPTION_KEYS) {
        if (key === "configOverridePatch") {
            applyConfigOverridePatchOverrides(target, source.configOverridePatch);
            continue;
        }
        if (source[key] === undefined) {
            continue;
        }
        assignWorkflowOptionField(target, key, source[key]);
    }
}
function applyConfigOverridePatchDefaults(target, sourcePatch) {
    if (sourcePatch === undefined) {
        return;
    }
    const targetPatch = target.configOverridePatch;
    if (targetPatch === undefined) {
        target.configOverridePatch = sourcePatch;
        return;
    }
    target.configOverridePatch = {
        entries: (0, command_apply_1.mergeConfigOverridePatchEntries)(sourcePatch.entries, targetPatch.entries, { keepInheritEntries: true }),
    };
}
function applyConfigOverridePatchOverrides(target, sourcePatch) {
    if (sourcePatch === undefined) {
        return;
    }
    target.configOverridePatch = {
        entries: (0, command_apply_1.mergeConfigOverridePatchEntries)(target.configOverridePatch?.entries, sourcePatch.entries, { keepInheritEntries: true }),
    };
}
function assignWorkflowOptionField(target, key, value) {
    target[key] = value;
}
