#pragma once
#include <SQLiteCpp/SQLiteCpp.h>
#include <vector>

class DB {
public:
  constexpr static const std::string DB_PATH = "/var/lib/shrap";

  void init_db() {
    m_db.exec(R"(
    CREATE TABLE IF NOT EXISTS installed (
      name TEXT PRIMARY KEY,
      version TEXT NOT NULL,
      installed_at INTEGER NOT NULL
    );
  )");
  }

  bool is_installed(const std::string &name) {
    SQLite::Statement query(m_db,
                            "SELECT version FROM installed WHERE name = ?");
    query.bind(1, name);
    return query.executeStep();
  }

  void mark_installed(const std::string &name, const std::string &version) {
    SQLite::Statement insert(
        m_db, "INSERT OR REPLACE INTO installed(name, version, "
              "installed_at) VALUES (?, ?, strftime('%s','now'))");

    insert.bind(1, name);
    insert.bind(2, version);
    insert.exec();
  }

  auto get_installed() {
    std::vector<std::pair<std::string, std::string>> installed;

    SQLite::Statement query(m_db, "SELECT name, version FROM installed");
    while (query.executeStep()) {
      std::string name = query.getColumn(0).getString();
      std::string version = query.getColumn(1).getString();
      installed.emplace_back(name, version);
    }

    return installed;
  }

private:
  SQLite::Database m_db{DB_PATH + "/shrap.db",
                        SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE};
};
