BareGit
#pragma once

#include <cstdint>
#include <optional>
#include <string>
#include <vector>

#include <mw/error.hpp>

namespace telegrammer
{

/// Identifies the API key that authenticated a request.
struct KeyIdentity
{
    /// Stable database identity of the key.
    int64_t id;
    /// Operator-assigned key name.
    std::string name;
};

/// Metadata exposed by key listing without credential material.
struct KeyInfo
{
    /// Stable database identity of the key.
    int64_t id;
    /// Operator-assigned key name.
    std::string name;
    /// Creation time as Unix seconds.
    int64_t created_at;
};

/// Provides credential creation, lookup, listing, and revocation.
class KeyStore
{
public:
    /// Construct a store backed by the supplied SQLite database.
    explicit KeyStore(std::string db_path);

    /// Generate and persist a new bearer credential.
    mw::E<std::string> addKey(const std::string& name) const;

    /// Resolve a bearer credential to its owning identity.
    mw::E<std::optional<KeyIdentity>> authenticate(
        const std::string& key) const;

    /// List key metadata without returning credential material.
    mw::E<std::vector<KeyInfo>> listKeys() const;

    /// Revoke a key and its owned subscriptions and deliveries.
    mw::E<bool> deleteKey(const std::string& name) const;

private:
    std::string db_path_;

    static mw::E<std::string> generateKey();
    static mw::E<std::string> digestKey(const std::string& key);
};

} // namespace telegrammer