# tests/testthat/test-pci_grid.R
# Test pci_grid output structure and values.

test_that("pci_grid returns correct structure (no CI)", {
  grid <- pci_grid("Cp",
                   LSL = 57, USL = 63,
                   sigma_vals = c(0.5, 1.0, 1.5),
                   mu = 60,
                   alpha_vals = c(0.05, 0.01))

  expect_s3_class(grid, "pci_grid")
  expect_s3_class(grid, "data.frame")

  # Expected columns
  expected_cols <- c("index", "sigma", "s", "p0", "alpha",
                     "estimate", "lower", "upper")
  expect_equal(names(grid), expected_cols)

  # 3 sigma_vals x 2 alpha_vals = 6 rows
  expect_equal(nrow(grid), 6)

  # All index values should be "Cp"
  expect_true(all(grid$index == "Cp"))

  # s and p0 should be NA
  expect_true(all(is.na(grid$s)))
  expect_true(all(is.na(grid$p0)))

  # lower and upper should be NA (n not supplied)
  expect_true(all(is.na(grid$lower)))
  expect_true(all(is.na(grid$upper)))
})

test_that("pci_grid computes correct estimates for Cp", {
  grid <- pci_grid("Cp",
                   LSL = 57, USL = 63,
                   sigma_vals = c(0.5, 1.0, 1.5),
                   mu = 60,
                   alpha_vals = c(0.05))

  estimates <- unique(grid$estimate)
  expected  <- c(2.0, 1.0, 6 / 9)
  expect_equal(sort(estimates), sort(expected), tolerance = 1e-4)
})

test_that("pci_grid with n produces CI bounds", {
  skip_on_cran()  # bootstrap is slow
  d <- pci_dist_normal(mean = 60, sd = 1)

  grid <- pci_grid("Cp",
                   dist = d,
                   LSL = 57, USL = 63,
                   sigma_vals = c(1.0),
                   mu = 60,
                   alpha_vals = c(0.05),
                   n = 30, B = 100)

  expect_equal(nrow(grid), 1)
  expect_false(is.na(grid$lower))
  expect_false(is.na(grid$upper))
  expect_true(grid$lower <= grid$upper)
})

test_that("pci_grid works for Cpy with p0_vals", {
  d <- pci_dist_normal(mean = 60, sd = 1)

  grid <- pci_grid("Cpy",
                   dist = d,
                   LSL = 57, USL = 63,
                   p0_vals = c(0.90, 0.95, 0.99),
                   alpha_vals = c(0.05))

  expect_equal(nrow(grid), 3)
  expect_true(all(!is.na(grid$estimate)))
  expect_true(all(!is.na(grid$p0)))
  expect_true(all(is.na(grid$sigma)))
  expect_true(all(is.na(grid$s)))
})
