import { Router } from "express";
import multer from "multer";
import { requireAuth } from "../middleware/auth.middleware.js";

import { apiReturn } from "../utils/returnHelper.utils.js";
import { abbottOrders } from "./logistics.dm.orders.map.abbott.js";
import { energizerOrders } from "./logistics.dm.orders.map.energizer.js";
import { macroImportOrders } from "./logistics.dm.orders.map.macroImport.js";
import { standardOrders } from "./logistics.dm.orders.map.standard.js";
import { scjOrders } from "./logistics.dm.orders.scj.js";

type ForecastResult = {
	success?: boolean;
	message?: string;
	data?: unknown;
};

const r = Router();

const upload = multer({
	storage: multer.memoryStorage(),
});

r.post("/", requireAuth, upload.single("file"), async (req, res) => {
	if (!req.file) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dm",
			subModule: "orders",
			message: "A file must be added to be able to run the forecast.",
			data: [],
			status: 400,
		});
	}

	const { fileType } = req.body;

	if (typeof fileType !== "string") {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dm",
			subModule: "orders",
			message: "A fileType must be provided.",
			data: [],
			status: 400,
		});
	}

	//console.log("fileType:", req.body.fileType);

	let result: ForecastResult;

	switch (fileType) {
		case "standard":
			result = await standardOrders(req.file, req.user);
			break;

		case "abbott":
			// daytons orders
			result = await abbottOrders(req.file, req.user);
			break;

		case "energizer":
			// daytons orders
			result = await energizerOrders(req.file, req.user);
			break;

		case "macro":
			result = await macroImportOrders(req.file, req.user);
			break;

		case "scj":
			// this is for west bend orders
			result = await scjOrders(req.file, req.user);
			break;

		default:
			return apiReturn(res, {
				success: false,
				level: "error",
				module: "dm",
				subModule: "orders",
				message: `Invalid fileType: ${fileType}`,
				data: [],
				status: 400,
			});
	}

	return apiReturn(res, {
		success: result.success ?? false,
		level: result.success ? "info" : "error",
		module: "dm",
		subModule: "orders",
		message: result.success
			? "The orders was accepted by Alplaprod 2.0 please check to make sure everything processed properly."
			: (result.message as string),
		data: result.data ?? ([] as any),
		status: result.success ? 200 : 500,
	});
});

export default r;
