#include "test_littlefs_common.h"

/* Opt in locally; the v5.x unit-test-app doesn't load this repo's sdkconfig.defaults. */
#define ESP_LITTLEFS_RAW_API
#include "lfs.h"

#ifndef LFS_CONFIG
#error "LFS_CONFIG was not exported to the consumer"
#endif

TEST_CASE("raw littlefs headers are exposed to consumers", "[littlefs_raw]")
{
    /* Declared only in include/lfs_config.h, not in upstream's lfs_util.h. */
    TEST_ASSERT_EQUAL_STRING("esp_littlefs", ESP_LITTLEFS_TAG);

    TEST_ASSERT_EQUAL_UINT32(4, lfs_alignup(3, 4));
    TEST_ASSERT_EQUAL_UINT32(0, lfs_aligndown(3, 4));
    TEST_ASSERT_LESS_THAN(0, LFS_ERR_CORRUPT);
}

/* Mount the raw API over the same partition the VFS layer uses and exchange
 * data both ways: the published headers must describe the on-disk format the
 * component writes. */
TEST_CASE("raw littlefs API is interchangeable with the VFS layer", "[littlefs_raw]")
{
    const esp_partition_t *part = get_test_data_partition();
    TEST_ASSERT_NOT_NULL(part);
    TEST_ESP_OK(esp_partition_erase_range(part, 0, part->size));

    struct lfs_config cfg;
    lfs_t lfs;
    test_littlefs_get_raw_cfg(&cfg);
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_format(&lfs, &cfg));
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_mount(&lfs, &cfg));

    lfs_file_t file;
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_file_open(&lfs, &file, "hello.txt", LFS_O_WRONLY | LFS_O_CREAT));
    TEST_ASSERT_EQUAL(strlen(littlefs_test_hello_str),
                      lfs_file_write(&lfs, &file, littlefs_test_hello_str, strlen(littlefs_test_hello_str)));
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_file_close(&lfs, &file));

    struct lfs_info info;
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_stat(&lfs, "hello.txt", &info));
    TEST_ASSERT_EQUAL(LFS_TYPE_REG, info.type);
    TEST_ASSERT_EQUAL(strlen(littlefs_test_hello_str), info.size);
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_unmount(&lfs));

    /* Mount VFS over the existing image; test_setup() would format it away. */
    const esp_vfs_littlefs_conf_t conf = {
        .base_path = littlefs_base_path,
        .partition_label = littlefs_test_partition_label,
        .format_if_mount_failed = false,
    };
    TEST_ESP_OK(esp_vfs_littlefs_register(&conf));
    test_littlefs_read_file_with_content(littlefs_base_path "/hello.txt", littlefs_test_hello_str);

    test_littlefs_create_file_with_text(littlefs_base_path "/from_vfs.txt", littlefs_test_hello_str);
    test_teardown();

    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_mount(&lfs, &cfg));
    char buf[32] = {0};
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_file_open(&lfs, &file, "from_vfs.txt", LFS_O_RDONLY));
    TEST_ASSERT_EQUAL(strlen(littlefs_test_hello_str), lfs_file_read(&lfs, &file, buf, sizeof(buf)));
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_file_close(&lfs, &file));
    TEST_ASSERT_EQUAL_STRING(littlefs_test_hello_str, buf);
    TEST_ASSERT_EQUAL(LFS_ERR_OK, lfs_unmount(&lfs));
}
