import { query } from "../../sqlServer/prodSqlServer.js";
import { deliveryByDateRangeAndAv } from "../../sqlServer/querys/dataMart/deleveryByDateRange.js";
import { addDays, format } from "date-fns";

export const getDeliveryByDateRangeAndAv = async (
    avs: string,
    startDate: string,
    endDate: string
) => {
    // const { data: plantToken, error: plantError } = await tryCatch(
    //     db.select().from(settings).where(eq(settings.name, "plantToken"))
    // );
    // if (plantError) {
    //     return {
    //         success: false,
    //         message: "Error getting Settings",
    //         data: plantError,
    //     };
    // }
    let deliverys: any = [];

    let updatedQuery = deliveryByDateRangeAndAv;

    // start days can be sent over
    if (startDate) {
        updatedQuery = updatedQuery.replaceAll("[startDate]", startDate);
    } else {
        updatedQuery = updatedQuery.replaceAll("[startDate]", "1990-1-1");
    }

    // end days can be sent over
    if (endDate) {
        updatedQuery = updatedQuery.replaceAll("[endDate]", endDate);
    } else {
        const defaultEndDate = format(
            addDays(new Date(Date.now()), 5),
            "yyyy-M-d"
        );
        updatedQuery = updatedQuery.replaceAll("[endDate]", defaultEndDate);
    }

    try {
        const res: any = await query(
            updatedQuery.replace("[articles]", avs),
            "Get Delivery by date range"
        );
        deliverys = res.data;
        //console.log(res.data);
    } catch (error) {
        console.log(error);
        return {
            success: false,
            message: "All Deliveries within the range.",
            data: error,
        };
    }

    // if (!data) {
    //     deliverys = deliverys.splice(1000, 0);
    // }
    // add plant token in
    // const pOrders = deliverys.map((item: any) => {
    //     // const dateCon = new Date(item.loadingDate).toLocaleString("en-US", {
    //     //     month: "numeric",
    //     //     day: "numeric",
    //     //     year: "numeric",
    //     //     hour: "2-digit",
    //     //     minute: "2-digit",
    //     //     hour12: false,
    //     // });

    //     //const dateCon = new Date(item.loadingDate).toISOString().replace("T", " ").split(".")[0];
    //     const dateCon = new Date(item.loadingDate).toISOString().split("T")[0];
    //     //const delDate = new Date(item.deliveryDate).toISOString().replace("T", " ").split(".")[0];
    //     const delDate = new Date(item.deliveryDate).toISOString().split("T")[0];
    //     return {
    //         plantToken: plantToken[0].value,
    //         ...item,
    //         loadingDate: dateCon,
    //         deliveryDate: delDate,
    //     };
    // });
    return { success: true, message: "Current open orders", data: deliverys };
};
