/**
 * Phase 1 we link the tag to the line only the line3.x where x is the line number
 * Phase 2 we will generate a label to be reprinted at staion 4
 */

import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { rfidReaders } from "../../../../../database/schema/rfidReaders.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import type { TagData } from "../tagData.js";
import { tagStuff } from "../tags/crudTag.js";

export const station3Tags = async (tagData: TagData[]) => {
    /**
     * Add the new tag to the reader so we know what was really here
     */
    const { error } = await tryCatch(
        db
            .update(rfidReaders)
            .set({ lastTagScanned: tagData[0].tag })
            .where(eq(rfidReaders.reader, tagData[0].reader))
    );
    if (error) {
        createLog(
            "error",
            "rfid",
            "rfid",
            `${tagData[0].reader} encountered and error adding ${tagData[0].tag}.`
        );
    }
    createLog(
        "info",
        "rfid",
        "rfid",
        `${tagData[0].reader} has a ${tagData[0].tag} will post it :)`
    );
    // make sure we only have one tag or dont update
    if (tagData.length != 1) {
        createLog(
            "error",
            "rfid",
            "rfid",
            `There are ${tagData.length} tags, and ${tagData[0].reader} only allows 1 tag to create a label.`
        );
        // get tag data

        for (let i = 0; i < tagData.length; i++) {
            const tag = {
                ...tagData[i],
                runningNr: 0,
                lastareaIn: "NeedsChecked",
            };
            tagStuff([tag]);
        }
    } else {
        //console.log("Generate the label and link it to the tag.");
        const tag = { ...tagData[0], runningNr: 0 };
        const tagdata = await tagStuff([tag]);

        createLog(
            "debug",
            "rfid",
            "rfid",
            "Generate a label and link it to this tag."
        );
    }
};
