import * as XLSX from "xlsx";
import { lanes } from "./cyclecountCheck.js";

export const lanesToExcel = async (age: string | null) => {
    // Convert JSON data to an array of arrays (AOA)

    let processLanes = lanes;
    if (age) {
        processLanes = lanes.filter(
            (l: any) => l.DaysSinceLast >= parseInt(age)
        );
    }

    const headers = Object.keys(processLanes[0]); // Get headers from JSON keys
    const data = processLanes.map((item: any) =>
        headers.map((header) => item[header])
    );

    // Create the workbook and worksheet
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([headers, ...data]); // Combine headers and data

    // Auto-resize columns based on the longest content in each column
    const colWidths = headers.map((_, colIndex) => {
        let maxLength = 0;
        data.forEach((row: any) => {
            const cellValue = row[colIndex] ? row[colIndex].toString() : "";
            maxLength = Math.max(maxLength, cellValue.length);
        });
        return { wch: maxLength + 2 }; // Add a little padding
    });

    ws["!cols"] = colWidths; // Set the column widths

    // Add the worksheet to the workbook
    XLSX.utils.book_append_sheet(wb, ws, "CycleCount");

    // Write the workbook to a buffer and return it
    const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "buffer" });

    return excelBuffer;
};
