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

export const postAdjustment = async (data: any) => {
	if (data.warehouseId === undefined) {
		return {
			sucess: false,
			message: `Missing mandatory field: warehouseID`,
			data: { error: `Missing mandatory field: warehouseID` },
		};
	}

	if (data.laneId === undefined) {
		return {
			sucess: false,
			message: `Missing mandatory field: locationID`,
			data: { error: `Missing mandatory field: locationID` },
		};
	}

	if (data.quantity == "0") {
		return {
			sucess: false,
			message: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
			data: {
				error: `You entered 0 for the quantity to post, quantity needs to be at leave 1`,
			},
		};
	}

	const siloAdjustment = {
		warehouseId: data.warehouseId,
		laneId: data.laneId,
		quantity: data.quantity,
	};

	let url = await prodEndpointCreation(
		"/public/v1.0/Warehousing/AdjustSiloStockLevel",
	);

	const { data: silo, error } = await tryCatch(
		axios.post(url, siloAdjustment, {
			headers: {
				"X-API-Key": process.env.TEC_API_KEY || "",
				"Content-Type": "application/json",
			},
		}),
	);
	let e = error as any;
	if (e) {
		console.log(e.response);
		if (e.status === 401) {
			const data = {
				success: false,
				message: `There was error posting the data: ${JSON.stringify(
					e.response?.data,
				)}`,
				data: {
					status: e.response?.status,
					statusText: e.response?.statusText,
					data: e.response?.data,
				},
			};
			return data;
		} else {
			return {
				success: false,
				message: "Error in posting the silo adjustment.",
				data: {
					status: e.response?.status,
					statusText: e.response?.statusText,
					data: e.response?.data,
				},
			};
		}
	}

	if (silo?.status !== 200) {
		return {
			success: false,
			message: "Error in posting the silo adjustment",
			data: {
				status: silo?.status,
				statusText: silo?.statusText,
				data: silo?.data,
			},
		};
	} else {
		return {
			success: true,
			message: "Adjustment was completed",
			data: {
				status: silo.status,
				statusText: silo.statusText,
				data: silo.data,
			},
		};
	}
};
