import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { notifications } from "../../../../../database/schema/notifications.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { sendEmail } from "../sendMail.js";
import { blockQuery } from "../../../sqlServer/querys/notifications/blocking.js";
export default async function qualityBlockingMonitor(notifyData: any) {
    createLog("info", "blocking", "notify", `monitoring ${notifyData.name}`);
    if (notifyData.emails === "") {
        createLog(
            "error",
            "blocking",
            "notify",
            `There are no emails set for ${notifyData.name}`
        );
        return {
            success: false,
            message: `There are no emails set for ${notifyData.name}`,
        };
    }

    const { data: noti, error: notiError } = await tryCatch(
        db
            .select()
            .from(notifications)
            .where(eq(notifications.name, notifyData.name))
    );

    if (notiError) {
        throw Error(`${JSON.stringify(notiError)}`);
    }

    const notiData: any = noti;
    const blockingOrders = notiData[0]?.notifiySettings.sentBlockingOrders.map(
        (l: any) => {
            return l.blockingOrder;
        }
    );

    // console.log(blockingOrders);

    // let blockingQuery = blockQuery.replaceAll(
    //     "[sentBlockingOrders]",
    //     blockingOrders
    // );

    let blockingQuery = blockQuery.replaceAll(
        "[lastBlocking]",
        notiData[0]?.notifiySettings.prodID
    );

    const { data: b, error: blockingError } = await tryCatch(
        query(blockingQuery, "Quality Blocking")
    );
    const blocking: any = b?.data as any;

    if (blockingError) {
        return {
            success: false,
            message: "Error getting blocking orders",
            data: blockingError,
        };
    }

    if (blocking.length > 0) {
        const emailSetup = {
            email: notifyData.emails,
            subject:
                blocking.length > 0
                    ? `Alert! New blocking orders.`
                    : blocking[0].subject,
            template: "qualityBlocking",
            context: {
                items: blocking,
            },
        };

        const { data: sentEmail, error: sendEmailError } = await tryCatch(
            sendEmail(emailSetup)
        );
        if (sendEmailError) {
            createLog(
                "error",
                "blocking",
                "notify",
                "Failed to send email, will try again on next interval"
            );
            return {
                success: false,
                message:
                    "Failed to send email, will try again on next interval",
            };
        }

        const newBlockingOrders = blocking.map((b: any) => {
            return {
                blockingOrder: b.HumanReadableId,
                timeStamp: new Date(Date.now()),
            };
        });
        const uniqueOrders = Array.from(
            new Set([
                ...notifyData.notifiySettings.sentBlockingOrders,
                ...newBlockingOrders,
            ])
        );

        console.log(uniqueOrders);
        const { data, error } = await tryCatch(
            db
                .update(notifications)
                .set({
                    lastRan: sql`NOW()`,
                    notifiySettings: {
                        ...notifyData.notifiySettings,
                        prodID: blocking[0].HumanReadableId,
                        sentBlockingOrders: uniqueOrders,
                    },
                })
                .where(eq(notifications.name, notifyData.name))
        );
        if (error) {
            createLog(
                "error",
                "blocking",
                "notify",
                "Error updating the blocking orders"
            );
            return {
                success: false,
                message: "Error updating the blocking orders",
                data: error,
            };
        }
    }

    return {
        success: true,
        message: "Blocking query ran successfully",
        blocking,
    };
}
