#include "db_utils.h"
#include <sqlite3.h>
#include <stdio.h>
#include <stdlib.h>

void db_initialize() {
  sqlite3 *db;
  char *err_msg = 0;
  int rc = sqlite3_open("database.db", &db);

  if (rc != SQLITE_OK) {
    fprintf(stderr, "Error: Cannot open database: %s\n", sqlite3_errmsg(db));
    return;
  }

  const char *sql =
      "CREATE TABLE IF NOT EXISTS kv_store (key TEXT PRIMARY KEY, value TEXT);";
  rc = sqlite3_exec(db, sql, 0, 0, &err_msg);

  if (rc != SQLITE_OK) {
    fprintf(stderr, "SQL error: %s\n", err_msg);
    sqlite3_free(err_msg);
  }

  sqlite3_close(db);
}

void test_db_set() {
  json_object *result = db_set("test_key", "test_value");
  if (result) {
    printf("db_set: %s\n", json_object_get_string(result));
    json_object_put(result);
  } else {
    printf("db_set failed\n");
  }
}

void test_db_get() {
  json_object *result = db_get("test_key");
  if (result) {
    printf("db_get: %s\n", json_object_to_json_string(result));
    json_object_put(result);
  } else {
    printf("db_get failed\n");
  }
}

void test_db_query() {
  json_object *result = db_query("SELECT * FROM kv_store");
  if (result) {
    printf("db_query: %s\n", json_object_to_json_string(result));
    json_object_put(result);
  } else {
    printf("db_query failed\n");
  }
}

int main() {
  db_initialize();
  test_db_set();
  test_db_get();
  test_db_query();
  return 0;
}