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

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

    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.status);
        if (results.data.errors) {
            createLog(
                "error",
                user.username,
                "logisitcs",
                results.data.errors[0].message
            );
            return {
                success: true,
                message: "Error processing orders",
                data: results.data.errors[0].message,
            };
        }

        if (results.status === 200) {
            createLog(
                "info",
                user.username,
                "logisitcs",
                "Orders were processed please check 2.0 for validation and errors"
            );
            return {
                success: true,
                message: "Success on posting orders",
                data: data,
            };
        }
    } catch (error: any) {
        //console.log(`There is an error`, error);
        if (error) {
            //console.log(error.response.data);
            createLog("error", user.username, "logisitcs", error.response.data);
            return {
                success: false,
                message: "There was an error processing data",
                data: error.response.data,
            };
        }
    }
};
