import { between, desc, gte, lte } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { siloAdjustments } from "../../../../../database/schema/siloAdjustments.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";

export const getSiloAdjustments = async (startDate: any, endDate: any) => {
    /**
     * Returns silo adjustments by date or all
     */

    if (startDate && endDate) {
        const { data: adjRange, error: adjRangeError } = await tryCatch(
            db
                .select()
                .from(siloAdjustments)
                .where(
                    between(
                        siloAdjustments.dateAdjusted,
                        new Date(startDate),
                        new Date(endDate)
                    )
                )
                .orderBy(desc(siloAdjustments.dateAdjusted))
        );

        if (adjRangeError) {
            return {
                success: false,
                message: "Error getting silo adjustments.",
                adjRangeError,
            };
        }

        return {
            success: true,
            message: "Silo adjustment data.",
            data: adjRange,
        };
    }

    if (startDate) {
        const { data: adjRange, error: adjRangeError } = await tryCatch(
            db
                .select()
                .from(siloAdjustments)
                .where(gte(siloAdjustments.dateAdjusted, new Date(startDate)))
                .orderBy(desc(siloAdjustments.dateAdjusted))
        );
        if (adjRangeError)
            return {
                success: false,
                message: "Error getting silo adjustments.",
                adjRangeError,
            };
        return {
            success: true,
            message: "Silo adjustment data.",
            data: adjRange,
        };
    }

    const { data: adjRange, error: adjRangeError } = await tryCatch(
        db
            .select()
            .from(siloAdjustments)
            .orderBy(desc(siloAdjustments.dateAdjusted))
    );
    if (adjRangeError)
        return {
            success: false,
            message: "Error getting silo adjustments.",
            adjRangeError,
        };
    return {
        success: true,
        message: "Silo adjustment data.",
        data: adjRange,
    };
};
