import { eq } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { deliveryByDateRange } from "../../sqlServer/querys/dataMart/deleveryByDateRange.js";
import { addDays, format } from "date-fns";

export const getDeliveryByDateRange = async (data: any | null) => {
    // 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 = deliveryByDateRange;

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

    // end days can be sent over
    if (data?.end) {
        updatedQuery = updatedQuery.replaceAll("[endDate]", data.end[0]);
    } 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,
            "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 };
};
