const { DateTime } = require("luxon");

module.exports = function (eleventyConfig, { TIME_ZONE }) {
    eleventyConfig.addDateParsing(function (dateValue) {
        // i know this is a deranged solution. sorry LOL
        let localDate;
        try {
            if (dateValue instanceof Date && !isNaN(dateValue)) {
                // handle filename dates (ie 2025-10-18-post.md)
                localDate = DateTime.fromJSDate(dateValue, { zone: "utc" })
                    .setZone(TIME_ZONE)
                    .startOf("day"); // Set to midnight in America/Santiago
            } else if (typeof dateValue === "string" && dateValue) {
                // handle string dates (ie from front matter, if used)
                localDate = DateTime.fromISO(dateValue, { zone: TIME_ZONE }).startOf("day");
            } else {
                // handle invalid input
                console.warn(`Invalid date value: ${dateValue} for ${this.page.inputPath}`);
                localDate = DateTime.now().setZone(TIME_ZONE).startOf("day");
            }
            if (!localDate || localDate.isValid === false) {
                throw new Error(`Invalid date value (${dateValue}) for ${this.page.inputPath}: ${localDate?.invalidReason || "Unknown"}`);
            }
            return localDate.toJSDate();
        } catch (error) {
            console.error(`Date parsing error for ${this.page.inputPath}:`, error.message);
            // fallback to current date in TIME_ZONE
            return DateTime.now().setZone(TIME_ZONE).startOf("day").toJSDate();
        }
    });
};
