#pragma once

#include "worker.h"
#include <thread>
#include <atomic>

class StockageManager : public Worker {
public:
    explicit StockageManager(ConnectionPool &pool, MessageBroker &broker);
    ~StockageManager() override;

protected:
    void run() override;

private:
    void addLocalStocks();
    std::vector<int> getTownIds();
    void addStockForTown(int townId);

    std::atomic<bool> addStocksRunning{true};
    std::thread addStocksThread;

    static constexpr const char *QUERY_GET_TOWNS = R"(
        SELECT fdr.id
        from falukant_data.region fdr
        join falukant_type.region ftr
          on ftr.id = fdr.region_type_id
        where ftr.label_tr = 'city'
    )";

    static constexpr const char *QUERY_INSERT_STOCK = R"(
        INSERT INTO falukant_data.buyable_stock (region_id, stock_type_id, quantity)
        SELECT
            $1 AS region_id,
            s.id      AS stock_type_id,
            GREATEST(1, ROUND(RANDOM() * 5 * COUNT(br.id))) AS quantity
        FROM
            falukant_data.branch        AS br
          CROSS JOIN
            falukant_type.stock         AS s
        WHERE
            br.region_id = $1
        GROUP BY
            s.id
        ORDER BY
            RANDOM()
        LIMIT
            GREATEST(
              ROUND(RANDOM() * (SELECT COUNT(id) FROM falukant_type.stock)),
              1
            );
    )";

    static constexpr const char *QUERY_CLEANUP_STOCK = R"(
        delete from falukant_data.buyable_stock
        where quantity <= 0
    )";
    void cleanupBuyableSotck();
};
