#include "Schema.h"
#include <io/debug.h>

#include "migrations/1624829187_create_events.h"
#include "migrations/1624964657_create_alarms.h"

namespace db {
  namespace db_builder = db::migrations::builder;

  Schema::Schema(sql::Database* db) : m_db(db) {
  }

  uint32_t Schema::get_user_version() const {
    try {
      int user_version = m_db->execAndGet("PRAGMA user_version;");
      return user_version;
    } catch (std::exception& e) {
      std::cout << "Exception: " << e.what() << std::endl;
      return -1;
    }
  }

  void Schema::set_user_version(uint32_t version) {
    try {
      m_db->exec("PRAGMA user_version = " + std::to_string(version) + ";");
      m_user_version = version;
    } catch (std::exception& e) {
      std::cout << "Exception: " << e.what() << std::endl;
    }
  }

  void Schema::set_savepoint() {
    try {
      m_db->exec("BEGIN;");
      m_db->exec("SAVEPOINT " + m_migration_savepoint + ";");
    } catch (std::exception& e) {
      std::cout << "Exception: " << e.what() << std::endl;
    }
  }

  void Schema::rollback_migrations() {
    try {
      m_db->exec("ROLLBACK TO " + m_migration_savepoint + ";");
    } catch (std::exception& e) {
      std::cout << "Exception: " << e.what() << std::endl;
    }
  }

  void Schema::commit_migrations() {
    try {
      m_db->exec("COMMIT;");
    } catch (std::exception& e) {
      std::cout << "Exception: " << e.what() << std::endl;
    }

  }

  uint32_t Schema::run_migrations() {
    assemble_migrations();
    if(migrations.begin() == migrations.end()) {
      DEBUG << "No migrations found...";
      return ERROR_NO_MIGRATIONS;
    }
    set_savepoint();
    uint32_t user_version = get_user_version();
    for(auto const& [epoch, migration] : migrations) {
      if(epoch <= user_version) {
        DEBUG << "Skipping: " << migration->get_migration_name();
        continue;
      }
      std::cout << "migrating: " << migration->get_migration_name() << std::endl;
      try {
        m_db->exec(migration->get_statement());
      } catch (std::exception& e) {
        std::cout << "Exception: " << e.what() << std::endl;
        std::cout << "Rolling back migrations..." << std::endl;
        rollback_migrations();
        return ERROR_FAULTY_MIGRATION;
      }
    }
    commit_migrations();
    set_user_version(migrations.rbegin()->first);
    return 0;
  }

  void Schema::assemble_migrations() {
    migrations.emplace(1624829187, new db::migrations::m1624829187_create_events());
    migrations.emplace(1624964657, new db::migrations::m1624964657_create_alarms());
  }
}