"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.pickRangeSelection = pickRangeSelection;
const date_fns_1 = require("date-fns");
/**
 * In the case where we have:
 * - Mode: "range"
 * - selected: { from: undefined, to: Date } or
 * - selected: { from: Date, to: undefined }
 *
 *
 * RDP returns undefined for newSelection. We need to manually handle these cases.
 */
function pickRangeSelection({ newSelection, currentSelection: selected, newDate, caller, }) {
    const skip = !(selected === null || selected === void 0 ? void 0 : selected.from) || !(selected === null || selected === void 0 ? void 0 : selected.to) || !caller;
    if (caller === "from" && !skip) {
        const to = selected === null || selected === void 0 ? void 0 : selected.to;
        if (!to) {
            return { from: newDate, to: undefined };
        }
        if ((0, date_fns_1.isSameDay)(newDate, to)) {
            return { from: newDate, to: newDate };
        }
        if ((0, date_fns_1.isBefore)(newDate, to)) {
            return { from: newDate, to };
        }
        /* newDate is after to — invalid range, clear to */
        return { from: newDate, to: undefined };
    }
    if (caller === "to" && !skip) {
        const from = selected === null || selected === void 0 ? void 0 : selected.from;
        if (!from) {
            return { from: newDate, to: undefined };
        }
        if ((0, date_fns_1.isSameDay)(newDate, from)) {
            return { from: newDate, to: newDate };
        }
        if ((0, date_fns_1.isBefore)(from, newDate)) {
            return { from, to: newDate };
        }
        /* newDate is before from — start fresh with newDate as the new from */
        return { from: newDate, to: undefined };
    }
    if (newSelection) {
        return newSelection;
    }
    // No caller - edge-case handling
    if (!(selected === null || selected === void 0 ? void 0 : selected.to)) {
        /**
         * If defaultSelected.from is defined, but not "to", and user selects the same date as "from",
         * we interpret this as user wanting to select a single date range (from === to).
         */
        if ((selected === null || selected === void 0 ? void 0 : selected.from) && (0, date_fns_1.isSameDay)(selected.from, newDate)) {
            return { from: newDate, to: newDate };
        }
        return { from: newDate, to: undefined };
    }
    let range;
    if ((0, date_fns_1.isSameDay)(selected.to, newDate)) {
        range = undefined;
    }
    else if ((0, date_fns_1.isBefore)(newDate, selected.to)) {
        range = { from: newDate, to: selected.to };
    }
    else {
        range = { from: selected.to, to: newDate };
    }
    return range;
}
//# sourceMappingURL=pick-range-selection.js.map