test_that("survey and census inputs are validated", {
  x <- inter_example()
  design <- inter_design(x$survey, "weight", "area", "strata", "psu")
  margins <- census_margins(x$margins)
  expect_s3_class(design, "inter_design")
  expect_s3_class(margins, "census_margins")
  expect_equal(length(margins$tables), 3L)
  expect_error(inter_design(x$survey, "missing", "area"), "not found")
})

test_that("fit reproduces margins and finite bounded estimates", {
  x <- inter_example()
  design <- inter_design(x$survey, "weight", "area", "strata", "psu")
  margins <- census_margins(x$margins)
  fit <- fit_inter_sae(
    unemployed ~ sex + age + residence + area,
    design, margins,
    family = "binomial",
    domain = c("area", "sex")
  )
  expect_s3_class(fit, "inter_sae")
  estimates <- inter_estimates(fit)
  expect_true(all(is.finite(estimates$estimate)))
  expect_true(all(estimates$estimate >= 0 & estimates$estimate <= 1))
  expect_lt(max(margin_diagnostics(fit)$relative_error), 1e-6)
  expect_equal(sum(estimates$population), margins$total)
})

test_that("rank diagnostic recognizes partial identification", {
  x <- inter_example()
  fit <- fit_inter_sae(
    unemployed ~ sex + age + residence + area,
    inter_design(x$survey, "weight", "area"),
    census_margins(x$margins),
    family = "binomial"
  )
  diagnostic <- check_identifiability(fit)
  expect_s3_class(diagnostic, "inter_identifiability")
  expect_gte(diagnostic$nullity, 0)
})

test_that("benchmarking reaches the requested aggregate", {
  x <- inter_example()
  fit <- fit_inter_sae(
    unemployed ~ sex + age + residence + area,
    inter_design(x$survey, "weight", "area"),
    census_margins(x$margins),
    family = "binomial"
  )
  target <- 0.3
  adjusted <- benchmark_inter(fit, target)
  expect_equal(attr(adjusted, "benchmark_achieved"), target, tolerance = 1e-8)
  expect_true(all(adjusted$benchmarked > 0 & adjusted$benchmarked < 1))
})
