/*
 * The MIT License (MIT)

 * Copyright (c) 2025 libsig Developers

 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef LIBSIG_COMMON_H_
#define LIBSIG_COMMON_H_

#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include <string>
#include <vector>

namespace libsig {

std::string binary_to_base64(const std::string &binary_data) {
  BIO *bio, *b64;
  BUF_MEM *bufferPtr;

  b64 = BIO_new(BIO_f_base64());
  bio = BIO_new(BIO_s_mem());
  bio = BIO_push(b64, bio);

  BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); // 不换行
  BIO_write(bio, binary_data.data(), static_cast<int>(binary_data.size()));
  BIO_flush(bio);
  BIO_get_mem_ptr(bio, &bufferPtr);

  std::string result(bufferPtr->data, bufferPtr->length);
  BIO_free_all(bio);

  return result;
}

std::string base64_to_binary(const std::string &base64_data) {
  BIO *bio, *b64;
  char *buffer = new char[base64_data.size()]; // 分配足够大的缓冲区

  b64 = BIO_new(BIO_f_base64());
  bio = BIO_new_mem_buf(base64_data.data(), static_cast<int>(base64_data.size()));
  bio = BIO_push(b64, bio);

  BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); // 不换行
  int decoded_length = BIO_read(bio, buffer, static_cast<int>(base64_data.size()));

  std::string result(buffer, decoded_length);
  BIO_free_all(bio);
  delete[] buffer;

  return result;
}

} // namespace libsig

#endif // LIBSIG_COMMON_H_