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 { consumptionCheck } from "../../sqlServer/querys/eom/consumptionCheck.js";
import { format } from "date-fns-tz";
import { regrindCheck } from "../../sqlServer/querys/eom/regrind.js";

type Consumption = {
    startDate: string;
    endDate: string;
    includePlantToken: boolean;
};

export const getRegrind = async (consumption: Consumption) => {
    const { data, error } = (await tryCatch(
        query(
            regrindCheck
                .replace("[startDate]", consumption.startDate)
                .replace("[endDate]", consumption.endDate),
            "Last sales price"
        )
    )) as any;

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

    if (consumption.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: `consumption data`,
            data: data.data.map((n: any) => {
                return {
                    plantToken: s[0].value,
                    ...n,
                    Buchungsdatum: format(n.Buchungsdatum, "M/d/yyyy"),
                };
            }),
        };
    } else {
        return {
            success: true,
            message: `consumption data`,
            data: data.data.map((n: any) => {
                return {
                    ...n,
                    Buchungsdatum: format(n.Buchungsdatum, "M/d/yyyy"),
                };
            }),
        };
    }
};
