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

export const lastPurchase = async (includePlantToken: boolean = false) => {
    const { data, error } = (await tryCatch(
        query(lastPurchasePrice, "Last purchase price")
    )) as any;

    if (error) {
        return {
            success: false,
            message: "Error getting the last purchase 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: `Last purchase price for all av in the last 5 years`,
            data: data.data.map((n: any) => {
                return { plantToken: s[0].value, ...n };
            }),
        };
    } else {
        return {
            success: true,
            message: `Last purchase price for all av in the last 5 years`,
            data: data.data,
        };
    }
};
