import { format } from "date-fns";
import { Router } from "express";
import { requireAuth } from "../middleware/auth.middleware.js";
import { excelTemplate, type Template } from "../utils/excelTemplates.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

r.get("/", requireAuth, async (req, res) => {
	const { filename } = req.query;

	const templateNames = ["orders", "forecast"];
	if (typeof filename !== "string" || !templateNames.includes(filename)) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dm",
			subModule: "template",
			message: "You are required to pass over the template name.",
			data: [],
			status: 500,
		});
	}

	const name = `${filename}-Template-${format(
		new Date(Date.now()),
		"M-d-yyyy",
	)}.xlsx`;

	const standardHeaders = [
		"CustomerArticleNumber",
		"CustomerOrderNumber",
		"CustomerLineNumber",
		"CustomerRealeaseNumber",
		"Quantity",
		"DeliveryDate",
		"CustomerID",
		"Remark",
		// "InvoiceID",
	];

	const forecastHeaders = [
		"CustomerArticleNumber",
		"Quantity",
		"RequirementDate",
		"CustomerID",
	];

	const template = {
		name,
		headers: filename === "orders" ? standardHeaders : forecastHeaders,
	} as Template;

	//console.log(template);
	const { data, error } = await tryCatch(excelTemplate(template));

	if (error || !data) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "dm",
			subModule: "template",
			message: "There was an error creating the Excel template.",
			data: [],
			status: 500,
		});
	}

	res.set({
		"Content-Type":
			"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
		"Content-Disposition": `attachment; filename="${name}"`,
	});

	return res.status(200).send(data);
});

export default r;
