#include "identity.h"

#ifdef VOICECAT_HAS_NET

#include <filesystem>
#include <stdexcept>

namespace voicecat::server {

bool ServerIdentityManager::init(const std::filesystem::path& data_dir,
                                  const std::string& server_name, std::string& error) {
    try {
        std::filesystem::create_directories(data_dir);

        auto id_path   = data_dir / "identity.key";
        auto cert_path = data_dir / "server.crt";
        auto key_path  = data_dir / "server.key";

        if (std::filesystem::exists(id_path) &&
            std::filesystem::exists(cert_path) &&
            std::filesystem::exists(key_path)) {
            identity_ = crypto::ServerIdentity::load(id_path);
            cert_     = crypto::ServerCert::load(cert_path, key_path);
        } else {
            identity_ = crypto::ServerIdentity::generate();
            cert_     = crypto::ServerCert::generate(server_name);
            identity_.save(id_path);
            cert_.save(cert_path, key_path);
        }
        return true;
    } catch (const std::exception& ex) {
        error = ex.what();
        return false;
    }
}

}  // namespace voicecat::server

#endif  // VOICECAT_HAS_NET
