test_that("convert_results_to_dataframe handles empty results", {
  result <- cloudosR:::convert_results_to_dataframe(list(), c("col1", "col2"))
  
  expect_s3_class(result, "data.frame")
  expect_equal(nrow(result), 0)
  expect_equal(ncol(result), 2)
  expect_equal(colnames(result), c("col1", "col2"))
})

test_that("convert_results_to_dataframe handles NULL values", {
  data <- list(
    list(col1 = "value1", col2 = NULL),
    list(col1 = NULL, col2 = "value2")
  )
  
  result <- cloudosR:::convert_results_to_dataframe(data, c("col1", "col2"))
  
  expect_s3_class(result, "data.frame")
  expect_equal(nrow(result), 2)
  expect_true(is.na(result[1, "col2"]))
  expect_true(is.na(result[2, "col1"]))
})


test_that("cloudos.query_submit_async validates inputs", {
  skip_on_cran()
  
  # Create a temporary config with a profile
  temp_config <- tempfile("cloudos_test_config")
  dir.create(temp_config, recursive = TRUE)
  old_env <- Sys.getenv("CLOUDOS_CONFIG_DIR", unset = NA)
  Sys.setenv(CLOUDOS_CONFIG_DIR = temp_config)
  
  on.exit({
    if (is.na(old_env)) {
      Sys.unsetenv("CLOUDOS_CONFIG_DIR")
    } else {
      Sys.setenv(CLOUDOS_CONFIG_DIR = old_env)
    }
    unlink(temp_config, recursive = TRUE)
  })
  
  # Create a test profile
  cloudos.configure(
    profilename = "test",
    apikey = "test-key",
    workspace_id = "test-workspace",
    set_default = TRUE
  )
  
  expect_error(
    cloudos.query_submit_async(profilename = "test", cohort_id = "", sql = "SELECT 1"),
    "cohort_id is required"
  )
  
  expect_error(
    cloudos.query_submit_async(profilename = "test", cohort_id = "123", sql = ""),
    "sql is required"
  )
})


test_that("cloudos.query validates poll_interval and max_wait", {
  skip_on_cran()
  
  # Create a temporary config with a profile
  temp_config <- tempfile("cloudos_test_config")
  dir.create(temp_config, recursive = TRUE)
  old_env <- Sys.getenv("CLOUDOS_CONFIG_DIR", unset = NA)
  Sys.setenv(CLOUDOS_CONFIG_DIR = temp_config)
  
  on.exit({
    if (is.na(old_env)) {
      Sys.unsetenv("CLOUDOS_CONFIG_DIR")
    } else {
      Sys.setenv(CLOUDOS_CONFIG_DIR = old_env)
    }
    unlink(temp_config, recursive = TRUE)
  })
  
  # Create a test profile
  cloudos.configure(
    profilename = "test",
    apikey = "test-key",
    workspace_id = "test-workspace",
    set_default = TRUE
  )
  
  expect_error(
    cloudos.query(
      profilename = "test",
      cohort_id = "123",
      sql = "SELECT 1",
      poll_interval = 0
    ),
    "poll_interval must be at least 1 second"
  )
  
  expect_error(
    cloudos.query(
      profilename = "test",
      cohort_id = "123",
      sql = "SELECT 1",
      max_wait = 0
    ),
    "max_wait must be at least 1 second"
  )
})
