// 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

/* This module current tests a small subset but should be extended in the future
 * for general ModuleDataType coverage.
 */

/* define macros for having usleep */
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#include <unistd.h>

#include "redictmodule.h"

static RedictModuleType *datatype = NULL;
static int load_encver = 0;

/* used to test processing events during slow loading */
static volatile int slow_loading = 0;
static volatile int is_in_slow_loading = 0;

#define DATATYPE_ENC_VER 1

typedef struct {
    long long intval;
    RedictModuleString *strval;
} DataType;

static void *datatype_load(RedictModuleIO *io, int encver) {
    load_encver = encver;
    int intval = RedictModule_LoadSigned(io);
    if (RedictModule_IsIOError(io)) return NULL;

    RedictModuleString *strval = RedictModule_LoadString(io);
    if (RedictModule_IsIOError(io)) return NULL;

    DataType *dt = (DataType *) RedictModule_Alloc(sizeof(DataType));
    dt->intval = intval;
    dt->strval = strval;

    if (slow_loading) {
        RedictModuleCtx *ctx = RedictModule_GetContextFromIO(io);
        is_in_slow_loading = 1;
        while (slow_loading) {
            RedictModule_Yield(ctx, REDICTMODULE_YIELD_FLAG_CLIENTS, "Slow module operation");
            usleep(1000);
        }
        is_in_slow_loading = 0;
    }

    return dt;
}

static void datatype_save(RedictModuleIO *io, void *value) {
    DataType *dt = (DataType *) value;
    RedictModule_SaveSigned(io, dt->intval);
    RedictModule_SaveString(io, dt->strval);
}

static void datatype_free(void *value) {
    if (value) {
        DataType *dt = (DataType *) value;

        if (dt->strval) RedictModule_FreeString(NULL, dt->strval);
        RedictModule_Free(dt);
    }
}

static void *datatype_copy(RedictModuleString *fromkey, RedictModuleString *tokey, const void *value) {
    const DataType *old = value;

    /* Answers to ultimate questions cannot be copied! */
    if (old->intval == 42)
        return NULL;

    DataType *new = (DataType *) RedictModule_Alloc(sizeof(DataType));

    new->intval = old->intval;
    new->strval = RedictModule_CreateStringFromString(NULL, old->strval);

    /* Breaking the rules here! We return a copy that also includes traces
     * of fromkey/tokey to confirm we get what we expect.
     */
    size_t len;
    const char *str = RedictModule_StringPtrLen(fromkey, &len);
    RedictModule_StringAppendBuffer(NULL, new->strval, "/", 1);
    RedictModule_StringAppendBuffer(NULL, new->strval, str, len);
    RedictModule_StringAppendBuffer(NULL, new->strval, "/", 1);
    str = RedictModule_StringPtrLen(tokey, &len);
    RedictModule_StringAppendBuffer(NULL, new->strval, str, len);

    return new;
}

static int datatype_set(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 4) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    long long intval;

    if (RedictModule_StringToLongLong(argv[2], &intval) != REDICTMODULE_OK) {
        RedictModule_ReplyWithError(ctx, "Invalid integer value");
        return REDICTMODULE_OK;
    }

    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);
    DataType *dt = RedictModule_Calloc(sizeof(DataType), 1);
    dt->intval = intval;
    dt->strval = argv[3];
    RedictModule_RetainString(ctx, dt->strval);

    RedictModule_ModuleTypeSetValue(key, datatype, dt);
    RedictModule_CloseKey(key);
    RedictModule_ReplyWithSimpleString(ctx, "OK");

    return REDICTMODULE_OK;
}

static int datatype_restore(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 4) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    long long encver;
    if (RedictModule_StringToLongLong(argv[3], &encver) != REDICTMODULE_OK) {
        RedictModule_ReplyWithError(ctx, "Invalid integer value");
        return REDICTMODULE_OK;
    }

    DataType *dt = RedictModule_LoadDataTypeFromStringEncver(argv[2], datatype, encver);
    if (!dt) {
        RedictModule_ReplyWithError(ctx, "Invalid data");
        return REDICTMODULE_OK;
    }

    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);
    RedictModule_ModuleTypeSetValue(key, datatype, dt);
    RedictModule_CloseKey(key);
    RedictModule_ReplyWithLongLong(ctx, load_encver);

    return REDICTMODULE_OK;
}

static int datatype_get(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 2) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_READ);
    DataType *dt = RedictModule_ModuleTypeGetValue(key);
    RedictModule_CloseKey(key);

    if (!dt) {
        RedictModule_ReplyWithNullArray(ctx);
    } else {
        RedictModule_ReplyWithArray(ctx, 2);
        RedictModule_ReplyWithLongLong(ctx, dt->intval);
        RedictModule_ReplyWithString(ctx, dt->strval);
    }
    return REDICTMODULE_OK;
}

static int datatype_dump(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 2) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    RedictModuleKey *key = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_READ);
    DataType *dt = RedictModule_ModuleTypeGetValue(key);
    RedictModule_CloseKey(key);

    RedictModuleString *reply = RedictModule_SaveDataTypeToString(ctx, dt, datatype);
    if (!reply) {
        RedictModule_ReplyWithError(ctx, "Failed to save");
        return REDICTMODULE_OK;
    }

    RedictModule_ReplyWithString(ctx, reply);
    RedictModule_FreeString(ctx, reply);
    return REDICTMODULE_OK;
}

static int datatype_swap(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 3) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    RedictModuleKey *a = RedictModule_OpenKey(ctx, argv[1], REDICTMODULE_WRITE);
    RedictModuleKey *b = RedictModule_OpenKey(ctx, argv[2], REDICTMODULE_WRITE);
    void *val = RedictModule_ModuleTypeGetValue(a);

    int error = (RedictModule_ModuleTypeReplaceValue(b, datatype, val, &val) == REDICTMODULE_ERR ||
                 RedictModule_ModuleTypeReplaceValue(a, datatype, val, NULL) == REDICTMODULE_ERR);
    if (!error)
        RedictModule_ReplyWithSimpleString(ctx, "OK");
    else
        RedictModule_ReplyWithError(ctx, "ERR failed");

    RedictModule_CloseKey(a);
    RedictModule_CloseKey(b);

    return REDICTMODULE_OK;
}

/* used to enable or disable slow loading */
static int datatype_slow_loading(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    if (argc != 2) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    long long ll;
    if (RedictModule_StringToLongLong(argv[1], &ll) != REDICTMODULE_OK) {
        RedictModule_ReplyWithError(ctx, "Invalid integer value");
        return REDICTMODULE_OK;
    }
    slow_loading = ll;
    RedictModule_ReplyWithSimpleString(ctx, "OK");
    return REDICTMODULE_OK;
}

/* used to test if we reached the slow loading code */
static int datatype_is_in_slow_loading(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    if (argc != 1) {
        RedictModule_WrongArity(ctx);
        return REDICTMODULE_OK;
    }

    RedictModule_ReplyWithLongLong(ctx, is_in_slow_loading);
    return REDICTMODULE_OK;
}

int createDataTypeBlockCheck(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);
    static RedictModuleType *datatype_outside_onload = NULL;

    RedictModuleTypeMethods datatype_methods = {
        .version = REDICTMODULE_TYPE_METHOD_VERSION,
        .rdb_load = datatype_load,
        .rdb_save = datatype_save,
        .free = datatype_free,
        .copy = datatype_copy
    };

    datatype_outside_onload = RedictModule_CreateDataType(ctx, "test_dt_outside_onload", 1, &datatype_methods);

    /* This validates that it's not possible to create datatype outside OnLoad,
     * thus returns an error if it succeeds. */
    if (datatype_outside_onload == NULL) {
        RedictModule_ReplyWithSimpleString(ctx, "OK");
    } else {
        RedictModule_ReplyWithError(ctx, "UNEXPECTEDOK");
    }
    return REDICTMODULE_OK;
}

int RedictModule_OnLoad(RedictModuleCtx *ctx, RedictModuleString **argv, int argc) {
    REDICTMODULE_NOT_USED(argv);
    REDICTMODULE_NOT_USED(argc);

    if (RedictModule_Init(ctx,"datatype",DATATYPE_ENC_VER,REDICTMODULE_APIVER_1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    /* Creates a command which creates a datatype outside OnLoad() function. */
    if (RedictModule_CreateCommand(ctx,"block.create.datatype.outside.onload", createDataTypeBlockCheck, "write", 0, 0, 0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    RedictModule_SetModuleOptions(ctx, REDICTMODULE_OPTIONS_HANDLE_IO_ERRORS);

    RedictModuleTypeMethods datatype_methods = {
        .version = REDICTMODULE_TYPE_METHOD_VERSION,
        .rdb_load = datatype_load,
        .rdb_save = datatype_save,
        .free = datatype_free,
        .copy = datatype_copy
    };

    datatype = RedictModule_CreateDataType(ctx, "test___dt", 1, &datatype_methods);
    if (datatype == NULL)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"datatype.set", datatype_set,
                                  "write deny-oom", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"datatype.get", datatype_get,"",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"datatype.restore", datatype_restore,
                                  "write deny-oom", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx,"datatype.dump", datatype_dump,"",1,1,1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx, "datatype.swap", datatype_swap,
                                  "write", 1, 1, 1) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx, "datatype.slow_loading", datatype_slow_loading,
                                  "allow-loading", 0, 0, 0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    if (RedictModule_CreateCommand(ctx, "datatype.is_in_slow_loading", datatype_is_in_slow_loading,
                                  "allow-loading", 0, 0, 0) == REDICTMODULE_ERR)
        return REDICTMODULE_ERR;

    return REDICTMODULE_OK;
}
