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

export const autoLabelCreated = async () => {
    const { error } = await tryCatch(
        db
            .insert(labelRatio)
            .values({
                name: "label",
                autoLabel: 1,
            })
            .onConflictDoUpdate({
                target: labelRatio.name,
                set: { autoLabel: sql`${labelRatio.autoLabel} + 1` },
            })
    );

    if (error) {
        createLog(
            "error",
            "labeling",
            "ocp",
            "There was an error updating auto label ratio"
        );
    }
};

export const manualLabelCreated = async () => {
    const { error } = await tryCatch(
        db
            .insert(labelRatio)
            .values({
                name: "label",
                manualLabel: 1,
            })
            .onConflictDoUpdate({
                target: labelRatio.name,
                set: { manualLabel: sql`${labelRatio.manualLabel} + 1` },
            })
    );

    if (error) {
        createLog(
            "error",
            "labeling",
            "ocp",
            "There was an error updating manual Label Ratio"
        );
    }
};

export const resetLabelRatio = async () => {
    const { error } = await tryCatch(
        db
            .update(labelRatio)
            .set({
                name: sql`'label-' || (SELECT count(*) FROM ${labelRatio})`,
                lastReset: sql`NOW()`,
            })
            .where(eq(labelRatio.name, "label"))
    );

    if (error) {
        console.log(error);
        createLog(
            "error",
            "labeling",
            "ocp",
            "There was an error resetting Label Ratio"
        );
        return {
            success: false,
            message: "There was an issue resetting the label data.",
        };
    }

    return {
        success: true,
        message: "Label Ratio has been reset.",
    };
};
