import { db } from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import { createLog } from "../../../logger/logger.js";

export const manualTag = async (
    tag: string,
    area: string,
    runningNr?: any | null
) => {
    /**
     * we only allow tags to be manually added from the wrappers
     */
    // create the proper string
    const number = tag.toString().padStart(9, "0");
    const tagString = `ALPLA${number}`;
    const newTag = {
        tagHex: Buffer.from(tagString, "utf8").toString("hex").toUpperCase(),
        tag: tagString,
        lastRead: new Date(Date.now()),
        counts: [{ area: area, timesHere: 1 }], //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
        lastareaIn: area,
        antenna: 0,
        tagStrength: -1,
    };
    try {
        // insert the tag with the onConflict update the tag
        const tag = await db
            .insert(rfidTags)
            .values(newTag)
            .returning({
                tag: rfidTags.tag,
                runningNumber: runningNr ? runningNr : rfidTags.runningNumber,
                counts: rfidTags.counts,
                lastareaIn: rfidTags.lastareaIn,
            })
            .onConflictDoUpdate({
                target: rfidTags.tagHex,
                set: {
                    lastRead: new Date(Date.now()),
                    lastareaIn: area,
                },
            });
        createLog(
            "info",
            "rfid",
            "rfid",
            `Tags were just added, and label printed.`
        );
        // do the label thing here
        return {
            success: true,
            message: `${tagString} was just added, and label printed.`,
            data: tag,
        };
    } catch (error) {
        createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
        return {
            success: false,
            message: `Error creating a new tag`,
            data: error,
        };
    }
};
