import axios from "axios";
import { prodEndpointCreation } from "../../../../../globalUtils/createUrl.js";
import { createLog } from "../../../../logger/logger.js";

export const postForecast = async (data: any, user: any) => {
    let endpoint = await prodEndpointCreation(
        "/public/v1.0/DemandManagement/DELFOR"
    );

    //console.log(endpoint);
    //console.log(req.body.orders[0]);
    try {
        const results = await axios({
            url: endpoint,
            method: "POST",
            headers: {
                "X-API-Key": process.env.TEC_API_KEY || "",
                "Content-Type": "application/json",
            },
            // if a body is sent over it would be like below
            data: data,
        });

        //console.log(results.data);
        //console.log(results.status);
        if (results.data.errors) {
            createLog(
                "error",
                "forecast",
                "logistics",
                `There was an error posting the Forecast: ${JSON.stringify(
                    results.data.errors
                )}`
            );
            return {
                success: true,
                message: "Error processing forecast",
                data: results.data.errors[0].message,
            };
        }

        if (results.status === 200) {
            createLog(
                "info",
                "forecast",
                "logistics",
                `Forcast was successfully posted: ${JSON.stringify(
                    results.data
                )}`
            );
            return {
                success: true,
                message: "Success on posting forecast",
                data: results.data,
            };
        }
    } catch (error: any) {
        //console.log(`There is an error`, error);
        if (error) {
            //console.log(error.response.data);
            createLog(
                "error",
                "forecast",
                "logistics",
                `There was an error posting the Forecast: ${JSON.stringify(
                    error.response.data
                )}`
            );
            return {
                success: false,
                message: "There was an error posting the Forecast",
                data: error.response.data,
            };
        }
    }
};
