import {z} from "zod";
import {createLog} from "../../logger/logger.js";
import {db} from "../../../../database/dbclient.js";
import {rfidReaders} from "../../../../database/schema/rfidReaders.js";

const ReaderData = z.object({
    reader: z.string(),
    readerIP: z.string(),
});

type ReaderData = z.infer<typeof ReaderData>;

export const addReader = async (data: ReaderData, user: any) => {
    /**
     * add a new reader with name and ip.
     */

    ReaderData.parse(data);

    if (!data.reader && !data.readerIP) {
        createLog("error", user.username, "rfid", "Missing data please check that you have both a name and ip.");
        return {success: false, message: "Missing data please check that you have both a name and ip."};
    }

    // try to add the reader
    try {
        await db.insert(rfidReaders).values(data).onConflictDoUpdate({target: rfidReaders.reader, set: data});
        createLog("info", user.username, "rfid", `Just added ${data.reader}.`);
        return {success: true, message: `${data.reader} was just added.`};
    } catch (error) {
        createLog("error", user.username, "rfid", `there was an error adding ${data.reader}, ${error}`);
        return {success: false, message: `${data.reader} encountered and error: ${error}`};
    }
};
