import {
    DSQL_DATASQUIREL_PROCESS_QUEUE,
    DsqlTables,
} from "../../../types/dsql";
import dsqlCrud from "../../../utils/data-fetching/crud";
import { DsqlCrudQueryObject, ServerQueryQueryObject } from "../../../types";

type Param = {
    queueId?: string | number;
    userId?: string | number;
    query?: DsqlCrudQueryObject<DSQL_DATASQUIREL_PROCESS_QUEUE>;
    single?: boolean;
};

export default async function getQueue({
    queueId,
    userId,
    query,
    single,
}: Param) {
    const tableName: (typeof DsqlTables)[number] = "process_queue";

    let queryQuery: ServerQueryQueryObject<DSQL_DATASQUIREL_PROCESS_QUEUE> = {};

    if (queueId) {
        queryQuery = { ...queryQuery, ...{ id: { value: String(queueId) } } };
    }

    if (userId) {
        queryQuery = {
            ...queryQuery,
            ...{ user_id: { value: String(userId) } },
        };
    }

    const getQueue = await dsqlCrud<DSQL_DATASQUIREL_PROCESS_QUEUE>({
        action: "get",
        table: tableName,
        query: {
            ...query,
            query: {
                ...query?.query,
                ...queryQuery,
            },
        },
    });

    const queuePayload = getQueue?.payload as
        | DSQL_DATASQUIREL_PROCESS_QUEUE[]
        | undefined;

    return queueId || single ? queuePayload?.[0] : queuePayload;
}
