// SPDX-FileCopyrightText: 2024 Redict Contributors
// SPDX-FileCopyrightText: 2024 Salvatore Sanfilippo <antirez at gmail dot com>
//
// SPDX-License-Identifier: BSD-3-Clause
// SPDX-License-Identifier: LGPL-3.0-only

#include "redictmodule.h"
#include <string.h>
#include <assert.h>
#include <unistd.h>

#define UNUSED(V) ((void) V)

int cmd_publish_classic_multi(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    if (argc < 3)
        return RedictModule_WrongArity(ctx);
    RedictModule_ReplyWithArray(ctx, argc-2);
    for (int i = 2; i < argc; i++) {
        int receivers = RedictModule_PublishMessage(ctx, argv[1], argv[i]);
        RedictModule_ReplyWithLongLong(ctx, receivers);
    }
    return REDICTMODULE_OK;
}

int cmd_publish_classic(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    if (argc != 3)
        return RedictModule_WrongArity(ctx);
    
    int receivers = RedictModule_PublishMessage(ctx, argv[1], argv[2]);
    RedictModule_ReplyWithLongLong(ctx, receivers);
    return REDICTMODULE_OK;
}

int cmd_publish_shard(RedictModuleCtx *ctx, RedictModuleString **argv, int argc)
{
    if (argc != 3)
        return RedictModule_WrongArity(ctx);
    
    int receivers = RedictModule_PublishMessageShard(ctx, argv[1], argv[2]);
    RedictModule_ReplyWithLongLong(ctx, receivers);
    return REDICTMODULE_OK;
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    UNUSED(argv);
    UNUSED(argc);
    
    if (RedictModule_Init(ctx,"publish",1,REDICTMODULE_APIVER_1)== REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"publish.classic",cmd_publish_classic,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"publish.classic_multi",cmd_publish_classic_multi,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"publish.shard",cmd_publish_shard,"",0,0,0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;
        
    return REDICTMODULE_OK;
}
