#include "tile/base/status.h"
#include "tile/base/internal/logging.h"

namespace tile {
Status::Status(int status, const std::string &desc)
{
    if (status == 0) {
        std::atomic<bool> flag{false};
        TILE_LOG_ERROR_IF_ONCE(!desc.empty(), "Status `SUCCESS` may not carry description but [{}] is given", desc);
    } else {
        state_         = MakeRefCounted<State>();
        state_->status = status;
        state_->desc   = desc;
    }
}

const std::string &
Status::message() const noexcept
{
    return state_ ? state_->desc : internal::EarlyInitConstant<std::string>();
}

std::string
Status::ToString() const
{
    return fmt::format("[{}] {}", code(), !ok() ? message() : "The operation completed successfully");
}

std::ostream &
operator<<(std::ostream &os, const Status &status)
{
    return os << status.ToString();
}

}// namespace tile
