#pragma once

#include "magic_strings.h"

#include <yandex/maps/wiki/revision/common.h>

#include <string>
#include <utility>
#include <map>
#include <set>

namespace maps::wiki::views {

struct QueryBuilder
{
public:
    explicit QueryBuilder(revision::DBID branchId);

    void with(const std::string& alias, const std::string& query);
    void with(
        const std::string& alias,
        const std::string& fields,
        const std::string& query);

    void selectFields(std::string str);
    void fromWith(const std::string& alias);

    template <class ...Args>
    void fromTable(const std::string& tableName, Args&& ...args)
    {
        fromTableInternal(tableName, std::set<std::string>{std::forward<Args>(args)...});
    }

    void whereClause(std::string str);

    std::string query() const;

private:
    void fromTableInternal(const std::string& tableName, const std::set<std::string>& aliases);

    struct WithData {
        std::string alias;
        std::string fields;
        std::string query;
    };

    revision::DBID branchId_;
    std::map<std::string, std::set<std::string>> fromTables_;
    std::vector<WithData> withData_;
    std::string selectFields_;
    std::string whereClause_;
    std::set<std::string> aliases_;
};

} // namespace maps::wiki::views
