import {addDays, format, subDays} from "date-fns";
import {db} from "../../../../database/dbclient.js";
import {settings} from "../../../../database/schema/settings.js";
import {prodEndpointCreation} from "../../../globalUtils/createUrl.js";
import axios from "axios";
import {lstAuth} from "../../../index.js";
import {createLog} from "../../logger/logger.js";

export const getShipmentData = async () => {
    let shiptmentInfo: any = [];
    let url = await prodEndpointCreation("/public/v1.0/Warehousing/GetTrucksAndLoadingPlans");
    const setting = await db.select().from(settings);
    const today = new Date(Date.now());
    const checkDays = parseInt(setting.filter((n) => n.name === "dayCheck")[0].value);

    const postData = {
        fromDate: `${format(subDays(today, checkDays), "yyyy-MM-dd")}`,
        toDate: `${format(addDays(today, checkDays), "yyyy-MM-dd")}`,
    };

    try {
        const result = await axios.post(url, postData, {headers: {Authorization: `Basic ${lstAuth}`}});
        shiptmentInfo = result.data;
        createLog("info", "ocme", "ocme", `Shipment info based on shipping id was just processed`);
        return {success: true, message: "Shipment data", data: shiptmentInfo};
    } catch (error) {
        createLog("error", "ocme", "ocme", `There was an error getting the shipment data: ${error}`);
        return {success: false, message: "Error in getting shipment data", data: error};
    }
};
