import { formatInTimeZone } from "date-fns-tz";
import { Router } from "express";
import { prodQuery } from "../prodSql/prodSqlQuery.controller.js";
import {
	type SqlQuery,
	sqlQuerySelector,
} from "../prodSql/prodSqlQuerySelector.utils.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

r.get("/", async (req, res) => {
	const { startDate, endDate, includePlantToken } = req.query;

	if (!startDate || startDate === "" || !endDate || endDate === "") {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "regrind",
			message: "The start date and end date are required to run this query.",
			data: [],
			status: 400,
		});
	}
	const sqlQuery = sqlQuerySelector(`eom.regrind`) as SqlQuery;

	if (!sqlQuery.success) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "regrind",
			message:
				"Failed to get regrind sql file please, please contact support if this continues.",
			data: [],
			status: 400,
		});
	}

	const { data, error } = await tryCatch(
		prodQuery(
			sqlQuery.query
				.replace("[startDate]", startDate as string)
				.replace("[endDate]", endDate as string),
			"Eom regrind data",
		),
	);

	if (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "regrind",
			message: `Error getting regrind data info`,
			data: error as any,
			notify: false,
			status: 400,
		});
	}

	return apiReturn(res, {
		success: data.success,
		level: data.success ? "info" : "error",
		module: "eom",
		subModule: "regrind",
		message: data.message,
		data:
			includePlantToken === "true" && data.success
				? data.data.map((i) => {
						return {
							plantToken: process.env.PROD_PLANT_TOKEN,
							...i,
							Buchungsdatum: formatInTimeZone(
								i.Buchungsdatum,
								"etc/utc",
								"M/d/yyyy",
							),
						};
					})
				: data.data.map((i) => {
						return {
							...i,
							Buchungsdatum: formatInTimeZone(
								i.Buchungsdatum,
								"etc/utc",
								"M/d/yyyy",
							),
						};
					}),
		notify: false,
		status: data.success ? 200 : 400,
	});
});

export default r;
