import { formatInTimeZone } from "date-fns-tz";
import { Router } from "express";
import { gpQuery } from "../gpSql/gpSqlQuery.controller.js";
import {
	type SqlGPQuery,
	sqlGpQuerySelector,
} from "../gpSql/gpSqlQuerySelector.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, glCode, includePlantToken } = req.query;

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

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

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

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

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

export default r;
