import { and, between, inArray, sql } from "drizzle-orm";
import { db } from "../../../../database/dbclient.js";
import { invHistoricalData } from "../../../../database/schema/historicalINV.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
import { createLog } from "../../logger/logger.js";

// type ArticleData = {
//     id: string
// }
export const psiGetInventory = async (
    avs: string,
    startDate: string,
    endDate: string
) => {
    let articles: any = [];

    if (!avs) {
        return {
            success: false,
            message: `Missing av's please send at least one over`,
            data: [],
        };
    }

    const ids = avs.split(",").map((id) => id.trim());

    const { data, error } = (await tryCatch(
        db
            .select()
            .from(invHistoricalData)
            .where(
                and(
                    inArray(invHistoricalData.article, ids),
                    between(invHistoricalData.histDate, startDate, endDate)
                )
            )
        //.limit(100)
    )) as any;

    if (error) {
        createLog(
            "error",
            "datamart",
            "datamart",
            `There was an error getting the planning info: ${JSON.stringify(
                error
            )}`
        );
        return {
            success: false,
            messsage: `There was an error getting the planning info`,
            data: error,
        };
    }

    articles = data;
    console.log(articles.length);
    return {
        success: true,
        message: "PSI planning Data",
        data: articles,
    };
};
