import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { rfidTags } from "../../../../../database/schema/rfidTags.js";
import type { TagData } from "../tagData.js";
import { createLog } from "../../../logger/logger.js";

type ReturnTag = {
    success: boolean;
    tag: any;
    error: any;
};
export const tagStuff = async (tagData: TagData[]): Promise<any> => {
    const tags = await db.select().from(rfidTags);

    // look through each tag and either add it to the db or update the area and other relevent data.
    for (let i = 0; i < tagData.length; i++) {
        // check if the tag already exists
        const tag = tags.filter((n) => n.tagHex === tagData[i].tagHex);
        if (tag.length === 0) {
            // add new tag
            const newTag = {
                tagHex: tagData[i].tagHex,
                tag: tagData[i].tag,
                lastRead: new Date(tagData[i].timeStamp),
                counts: [{ area: tagData[i].reader, timesHere: 1 }], //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
                lastareaIn: tagData[i].reader,
                antenna: tagData[i].antenna,
                tagStrength: tagData[i].tagStrength,
                runningNumber: tagData[i].runningNumber
                    ? tagData[i].runningNumber
                    : null,
            };
            try {
                // insert the tag with the onConflict update the tag
                const tag = await db
                    .insert(rfidTags)
                    .values(newTag)
                    .onConflictDoUpdate({
                        target: rfidTags.tagHex,
                        set: newTag,
                    })
                    .returning({
                        tag: rfidTags.tag,
                        runningNumber: rfidTags.runningNumber,
                        counts: rfidTags.counts,
                        lastareaIn: rfidTags.lastareaIn,
                    });
                createLog("info", "rfid", "rfid", `Tags were jusdt updated.`);
                return { success: true, tag };
            } catch (error) {
                createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
                return { success: false, error };
            }
        } else {
            // update tag
            //console.log("Updating existing tag");
            // make sure we actually have an array here
            const countsArray =
                (tag[0]?.counts as { area: string; timesHere: number }[]) ?? [];

            // check if the reader exists on the array
            const areaExists = countsArray.some(
                (t) => t.area === tagData[0].reader
            );

            // run the update on the array
            const updateCount = areaExists
                ? countsArray.map((t) => {
                      if (t.area === tagData[0].reader) {
                          return { ...t, timesHere: t.timesHere + 1 };
                      } else {
                          return {
                              ...t,
                              area: tagData[i].reader,
                              timesHere: 1,
                          };
                      }
                  })
                : [...countsArray, { area: tagData[i].reader, timesHere: 1 }];

            const updateTag = {
                lastRead: new Date(tagData[i].timeStamp),
                counts: updateCount, //jsonb("counts").notNull(), //.default([{area: 1, timesHere: 5}]).notNull(),
                lastareaIn: tagData[i].reader,
                antenna: tagData[i].antenna,
                tagStrength: tagData[i].tagStrength,
            };

            try {
                await db
                    .update(rfidTags)
                    .set(updateTag)
                    .where(eq(rfidTags.tagHex, tagData[0].tagHex))
                    .returning({
                        tag: rfidTags.tag,
                        runningNumber: rfidTags.runningNumber,
                        counts: rfidTags.counts,
                        lastareaIn: rfidTags.lastareaIn,
                    });
                createLog("info", "rfid", "rfid", `Tags were jusdt updated.`);
                return { success: true, tag };
            } catch (error) {
                createLog("error", "rfid", "rfid", `${JSON.stringify(error)}`);
                return { success: false, error };
            }
        }
    }
};
