#pragma once
#include "db/database.hpp"
#include "utils/migration-manager/migration-manager.hpp"
#include <optional>
#include <qlogging.h>
#include <filesystem>

static constexpr const char *OMNI_PRAGMAS[] = {"PRAGMA journal_mode = WAL", "PRAGMA foreign_keys = ON"};

class OmniDatabase {
  db::Database _db;

public:
  db::Database &db() { return _db; }

  OmniDatabase(const std::filesystem::path &path, std::optional<db::EncryptionKey> key = std::nullopt) {
    auto result = db::Database::open(path);

    if (!result) {
      qCritical() << "Could not open main omnicast SQLite database:" << result.error().c_str();
      return;
    }

    _db = std::move(*result);

    if (key) {
      if (auto unlocked = _db.setKey(*key); !unlocked)
        qFatal("Could not unlock encrypted database: %s", unlocked.error().c_str());
    }

    for (const auto &pragma : OMNI_PRAGMAS) {
      _db.exec(pragma);
    }

    MigrationManager manager(_db, "omnicast");

    manager.runMigrations();
  }
};
