import { query } from "../services/sqlServer/prodSqlServer.js";
import { plantInfo } from "../services/sqlServer/querys/dataMart/plantInfo.js";
import { createLog } from "../services/logger/logger.js";
import { getSettings } from "../services/server/controller/settings/getSettings.js";

export const createSSCC = async (runningNumber: number) => {
    // get the token

    let serverSettings = (await getSettings()) as any;
    const plantToken = serverSettings?.filter(
        (n: any) => n.name === "plantToken"
    );
    // const plantToken = await db
    //     .select()
    //     .from(settings)
    //     .where(eq(settings.name, "plantToken"));
    let global: any = []; // get from plant address in basis enter the entire string here.

    try {
        const res: any = await query(
            plantInfo.replaceAll("[token]", plantToken[0].value),
            "plantInfo"
        );
        global = res.data;
    } catch (error) {
        createLog(
            "error",
            "lst",
            "globalUtils",
            `There was an error getting the GLN: Error: ${error}`
        );
    }

    // create the sscc without the check diget and make sure we have it all correct

    let step1SSCC =
        global[0].gln.toString().slice(0, 7).padStart(10, "0") +
        runningNumber.toString().padStart(9, "0");

    let sum = 0;
    for (let i = 0; i < step1SSCC.length; i++) {
        let digit = parseInt(step1SSCC[i], 10);
        if (i % 2 === 0) {
            // Even index in 0-based index system means odd position in 1-based index system
            sum += digit * 3;
        } else {
            sum += digit;
        }
    }
    let checkDigit = (10 - (sum % 10)) % 10;

    // make sure the check digit is never 10

    // let checkDigit = 10 - ((oddSum * 3 + evenSum) % 10) === 10 ? 0 : (oddSum * 3 + evenSum) % 10;

    // return the true sscc
    let sscc = step1SSCC + checkDigit;
    // console.log(step1SSCC);
    // console.log(checkDigit);
    return sscc.padStart(20, "0");
};

// let rn = 518475;

// console.log(`Creating sscc`);
// let sscc = await createSSCC(rn);
// console.log(sscc);
