// SELECT count(*) FROM V_EtikettenGedruckt where AnzahlGedruckterKopien > 2 and CONVERT(varchar(5), Add_Date,108) not like CONVERT(varchar(5), Upd_Date,108) and Upd_Date > DATEADD(SECOND, -30,getdate()) and VpkVorschriftBez not like '%$%'

import { isWeekend } from "date-fns";
import { createLog } from "../../../logger/logger.js";
import { sendEmail } from "../sendMail.js";
import { query } from "../../../sqlServer/prodSqlServer.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { notifications } from "../../../../../database/schema/notifications.js";
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";

export interface PPOO {
    IdPosition?: number;
}
export default async function reprintLabelMonitor(notifyData: any) {
    createLog("info", "notify", "notify", `monitoring ${notifyData.name}`);
    if (notifyData.emails === "") {
        createLog(
            "error",
            "notify",
            "notify",
            `There are no emails set for ${notifyData.notificationName}`
        );

        return;
    }

    // as this one goes to managers we want to not send on the weekends

    const weekend = isWeekend(new Date(Date.now()));

    if (weekend && notifyData.notifiySettings.weekend) {
        createLog(
            "info",
            "notify",
            "notify",
            `${notifyData.name} will not run on the weekends`
        );
        return;
    }

    let noteQuery = `
        SELECT 
      --[EinlagerungsDatummin] as lastMovingDate,
      round(VerfuegbareMengeVPKSum,2) as pallets
      ,VerfuegbareMengeSum as total
      ,round([GesperrteMengeVpkSum],2) as held
	  ,round([GesperrteMengeSum],2) as heldQty
      ,[IdArtikelVarianten] as av
      ,[IdProdBereich] as pfcID
      ,[ArtikelVariantenBez] as articleDescription
      ,[ArtikelVariantenAlias] as articleDescriptionAlias
	  ,[LagerAbteilungKurzBez] as location
      ,[Lfdnr] as runningNumber
      ,[Produktionslos] as lot
      ,[ProduktionsDatumMin] as productionDate   
      ,IdPosition  
        FROM [AlplaPROD_test1].[dbo].[V_LagerPositionenBarcodes] (nolock)

        where idlagerabteilung in ([locations]) and [ProduktionsDatumMin] < DATEadd( Hour, -[timeCheck], getdate())

        order by [ProduktionsDatumMin] asc
        `;

    //update the time check
    noteQuery = noteQuery
        .replaceAll("[timeCheck]", notifyData.checkInterval)
        .replaceAll("[locations]", notifyData.notifiySettings.locations);

    let stage: PPOO[];
    try {
        const res = await query(noteQuery, "Staging checks");
        stage = res?.data as any;
        //console.log(labels.length);
        // const now = Date.now()
        if (stage.length > 0) {
            //send the email :D

            // update the count with the result

            const emailSetup = {
                email: notifyData.emails,
                subject: `Alert! Pallets in staging greater than ${notifyData.checkInterval} ${notifyData.timeType}`,
                template: "stagingCheck",
                context: {
                    items: stage,
                    count: stage.length,
                    checkTime: notifyData.checkInterval,
                    timeCheck: notifyData.timeType,
                },
            };

            const sentEmail = await sendEmail(emailSetup);

            if (!sentEmail.success) {
                createLog(
                    "error",
                    "notify",
                    "notify",
                    "Failed to send email, will try again on next interval"
                );
                return;
            }

            // update the last time we ran and the prod id
            let updateSettings = notifyData.notifiySettings;
            const { data, error } = await tryCatch(
                db
                    .update(notifications)
                    .set({
                        lastRan: sql`NOW()`,
                        notifiySettings: {
                            ...updateSettings,
                            count: stage.length,
                        },
                    })
                    .where(eq(notifications.name, notifyData.name))
            );
        } else {
            return;
        }
    } catch (err) {
        createLog(
            "error",
            "notify",
            "notify",
            `Error from running the Label Reprints query: ${err}`
        );
    }
}
