import { eq } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { settings } from "../../../../database/schema/settings.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { query } from "../../sqlServer/prodSqlServer.js";
import { lastSalesPriceCheck } from "../../sqlServer/querys/eom/lastSalesprice.js";
import { format } from "date-fns-tz";

export const lastSales = async (
    date: string,
    includePlantToken: boolean = false
) => {
    const { data, error } = (await tryCatch(
        query(lastSalesPriceCheck.replace("[date]", date), "Last sales price")
    )) as any;

    if (error) {
        return {
            success: false,
            message: "Error getting the last sales price",
            data: error,
        };
    }

    if (includePlantToken) {
        const { data: s, error: se } = (await tryCatch(
            db.select().from(settings).where(eq(settings.name, "plantToken"))
        )) as any;

        if (se) {
            console.log("Error getting articles");
            return data.data;
        }

        return {
            success: true,
            message: `Historical inventory for ${date}`,
            data: data.data.map((n: any) => {
                return {
                    plantToken: s[0].value,
                    ...n,
                    validDate: format(n.validDate, "M/d/yyyy"),
                };
            }),
        };
    } else {
        return {
            success: true,
            message: `Last sales price for all av in the last 5 years`,
            data: data.data.map((n: any) => {
                return { ...n, validDate: format(n.validDate, "M/d/yyyy") };
            }),
        };
    }
};
