// SPDX-FileCopyrightText: 2024 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later

#include "publish.h"

#include <exception>

Module::Publish::Publish(const std::shared_ptr<Core>& core, const Config::Module& conf):
    Module(core, conf, "Publish")
{}

Module::Publish::~Publish() noexcept {}

Shared::Result Module::Publish::message(const std::shared_ptr<::Actor>& actor, std::string_view view) {
    std::string_view command = pop(view);

    if (command == "to") {
        if (!hasPermission("publish", actor))
            return Shared::forbidden;
        
        std::string_view head = pop(view, '\n');
        std::string_view address = pop(head);
        if (address.empty())
            return Shared::error;

        return to(address, head, view);
    }

    return Shared::unhandled;
}

Shared::Result Module::Publish::to(std::string_view address, std::string_view title, std::string_view body) {
    std::string_view node = pop(address, '@');
    if (node.empty() || address.empty()) {
        warn("Malformed address in \"to\" method");
        return Shared::error;
    }

    try {
        core->publish(std::string(address), std::string(node), std::string(title), std::string(body));
        return Shared::success;
    } catch (const std::exception& e) {
        error("Exception in \"to\" method: " + std::string(e.what()));
    } catch (...) {
        error("Unhandled exception in \"to\" method");
    }

    return Shared::error;
}