import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { siloAdjustments } from "../../../../../database/schema/siloAdjustments.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";

export const postSiloComment = async (
    id: string,
    comment: string,
    commentk: string,
    user: any
) => {
    /**
     * We will add the comment to the silo adjustment so we know the why we had this.
     */

    // make sure we havea  valid key
    const { data: key, error: keyErro } = await tryCatch(
        db
            .select()
            .from(siloAdjustments)
            .where(eq(siloAdjustments.siloAdjust_id, id))
    );

    if (keyErro) {
        return {
            success: false,
            message: "There was an error getting the adjustment.",
            data: keyErro,
        };
    }

    if (key[0].commentKey != commentk) {
        return {
            success: false,
            message: "The key you provided is invalid.",
            data: keyErro,
        };
    }

    const { data, error } = await tryCatch(
        db
            .update(siloAdjustments)
            .set({
                comment: comment,
                commentAddedBy: user.username,
                commentDate: sql`NOW()`,
                commentKey: null,
            })
            .where(eq(siloAdjustments.siloAdjust_id, id))
    );

    if (error) {
        return {
            success: false,
            message: "There was an error adding the comment.",
            data: error,
        };
    }

    return {
        success: true,
        message: "Comment was successfully added.",
    };
};
