# tests/testthat/test-validation.R
# Test that input validation produces clear errors.

test_that("USL <= LSL produces an error", {
  expect_error(pci("Cp", LSL = 63, USL = 57, sigma = 1),
               "USL must be greater than LSL")
  expect_error(pci("Cp", LSL = 60, USL = 60, sigma = 1),
               "USL must be greater than LSL")
})

test_that("negative or zero sigma produces an error", {
  expect_error(pci("Cp", LSL = 57, USL = 63, sigma = -1),
               "positive")
  expect_error(pci("Cp", LSL = 57, USL = 63, sigma = 0),
               "positive")
})

test_that("negative or zero s produces an error", {
  expect_error(pci("Pp", LSL = 57, USL = 63, s = -1),
               "positive")
  expect_error(pci("Pp", LSL = 57, USL = 63, s = 0),
               "positive")
})

test_that("invalid alpha produces an error in pci_ci", {
  d <- pci_dist_normal(mean = 60, sd = 1)
  expect_error(pci_ci("Cp", dist = d, n = 30, LSL = 57, USL = 63, alpha = 0),
               "alpha.*between 0 and 1")
  expect_error(pci_ci("Cp", dist = d, n = 30, LSL = 57, USL = 63, alpha = 1),
               "alpha.*between 0 and 1")
  expect_error(pci_ci("Cp", dist = d, n = 30, LSL = 57, USL = 63, alpha = -0.5),
               "alpha.*between 0 and 1")
  expect_error(pci_ci("Cp", dist = d, n = 30, LSL = 57, USL = 63, alpha = 1.5),
               "alpha.*between 0 and 1")
})

test_that("Cpy without dist produces an error", {
  expect_error(pci("Cpy", LSL = 57, USL = 63, p0 = 0.95),
               "pci_dist")
})

test_that("Cpy without p0 or LDL/UDL produces an error", {
  d <- pci_dist_normal(mean = 60, sd = 1)
  expect_error(pci("Cpy", dist = d, LSL = 57, USL = 63),
               "LDL.*UDL.*p0")
})

test_that("invalid index name produces an error", {
  expect_error(pci("InvalidIndex"),
               "'arg' should be one of")
})

test_that("pci_dist with non-function pdf produces an error", {
  expect_error(pci_dist(pdf = "not_a_function"),
               "function")
})

test_that("missing required parameters produce errors", {
  expect_error(pci("Cp", LSL = 57, USL = 63),
               "sigma")
  expect_error(pci("Cpk", LSL = 57, USL = 63, sigma = 1),
               "mu")
  expect_error(pci("Cpm", LSL = 57, USL = 63, mu = 60, sigma = 1),
               "target")
  expect_error(pci("Ppk", LSL = 57, USL = 63, s = 1.5),
               "xbar")
})

test_that("pci_dist_normal with invalid sd produces an error", {
  expect_error(pci_dist_normal(mean = 0, sd = -1), "positive")
  expect_error(pci_dist_normal(mean = 0, sd = 0),  "positive")
})

test_that("pci_dist with bad support produces an error", {
  expect_error(
    pci_dist(pdf = dnorm, support = c(10, 5)),
    "support"
  )
})
