import getQueue from "./get-queue";
import {
    DSQL_DATASQUIREL_PROCESS_QUEUE,
    DsqlTables,
} from "../../../types/dsql";
import dsqlCrud from "../../../utils/data-fetching/crud";
import numberfy from "../../../utils/numberfy";

type Param = {
    queue: DSQL_DATASQUIREL_PROCESS_QUEUE;
    userId: string | number;
    dummy?: boolean;
};

export default async function addQueue({ queue, userId, dummy }: Param) {
    const tableName: (typeof DsqlTables)[number] = "process_queue";

    const existingQueueRes = dummy
        ? undefined
        : ((await getQueue({
              query: {
                  query: {
                      user_id: {
                          value: String(userId),
                      },
                      job_type: {
                          value: String(queue.job_type),
                      },
                  },
              },
          })) as DSQL_DATASQUIREL_PROCESS_QUEUE[] | undefined);

    const existingQueue = existingQueueRes?.[0];

    if (existingQueue?.id && !dummy) return undefined;

    const addQueueRes = await dsqlCrud<DSQL_DATASQUIREL_PROCESS_QUEUE>({
        action: "insert",
        table: tableName,
        data: { ...queue, user_id: numberfy(userId) },
    });

    return addQueueRes;
}
