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 { date, includePlantToken } = req.query;

	if (!date || date === "") {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "lastSalesPrice",
			message: "A date is required to run this query.",
			data: [],
			status: 400,
		});
	}
	const sqlQuery = sqlQuerySelector(`eom.lastSalesPrice`) as SqlQuery;

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

	const { data, error } = await tryCatch(
		prodQuery(
			sqlQuery.query.replace("[date]", date as string),

			"Eom last sales price data",
		),
	);

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

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

export default r;
