import { format } from "date-fns";
import { eq } from "drizzle-orm";
import { Router } from "express";
import { db } from "../db/db.controller.js";
import { invHistoricalData } from "../db/schema/historicalInv.schema.js";
import { apiReturn } from "../utils/returnHelper.utils.js";
import { tryCatch } from "../utils/trycatch.utils.js";

const r = Router();

r.get("/", async (req, res) => {
	// the params we are wanting to add in. min required will be the month so we dont pass everything over
	const { date } = req.query;

	if (!date || date === "") {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "historical inv",
			message:
				"The day of the month is required to be included in order to pass.",
			data: [],
			status: 400,
		});
	}

	// get the date passed over.
	const { data, error } = await tryCatch(
		db
			.select()
			.from(invHistoricalData)
			.where(
				eq(invHistoricalData.histDate, format(date as string, "yyyy-MM-dd")),
			),
	);

	if (error) {
		return apiReturn(res, {
			success: false,
			level: "error",
			module: "eom",
			subModule: "historical inv",
			message:
				"There was an error getting the historical data from the server.",
			data: error as any,
			status: 400,
		});
	}

	return apiReturn(res, {
		success: true,
		level: "info",
		module: "eom",
		subModule: "historical inv",
		message: "Eom Historical Inv Data",
		data: data,
		status: 200,
	});
});
export default r;
