import { Router } from "express";
import multer from "multer";
import { requireAuth } from "../middleware/auth.middleware.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { energizerForecast } from "./logistics.dm.forecast.map.energizer.js";
import { lorealForecast } from "./logistics.dm.forecast.map.loreal.js";
import { pNgForecast } from "./logistics.dm.forecast.map.pNg.js";
import { standardForecast } from "./logistics.dm.forecast.map.standard.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: "forecast",
			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: "forecast",
			message: "A fileType must be provided.",
			data: [],
			status: 400,
		});
	}

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

	let result: ForecastResult;

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

		case "loreal":
			result = await lorealForecast(req.file, req.user);
			break;

		case "pg":
			result = await pNgForecast(req.file, req.user);
			break;

		case "energizer":
			result = await energizerForecast(req.file, req.user);
			break;

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

	return apiReturn(res, {
		success: result.success ?? false,
		level: result.success ? "info" : "error",
		module: "dm",
		subModule: "forecast",
		message: result.success
			? "The forecast 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 : 400,
	});
});

export default r;
