require "minitest/autorun"
require_relative "support/stubs"

# Tests for DB.validate_table_name!
# The stub in support/stubs.rb implements the same regex as lib/db.rb,
# so these tests validate the intended allowlist pattern.

class TestDbValidateTableName < Minitest::Test
  # --- Valid names ---

  def test_simple_council_name
    assert_equal "da_brighton", DB.validate_table_name!("da_brighton")
  end

  def test_hyphenated_council_name
    assert_equal "da_break_oday", DB.validate_table_name!("da_break_oday")
  end

  def test_council_with_numbers
    assert_equal "da_waratah_wynyard", DB.validate_table_name!("da_waratah_wynyard")
  end

  def test_all_known_tables
    known = %w[
      da_break_oday da_brighton da_burnie da_centralcoast da_centralhighlands
      da_circularhead da_clarence da_derwentvalley da_devonportcity da_dorset
      da_flinders_council da_georgetown da_glamorgan da_glenorchy da_hobartcity
      da_huonvalley da_kentish da_kingborough da_latrobe da_launcestoncity
      da_meandervalley da_northernmidlands da_southernmidlands da_tasman
      da_waratah_wynyard da_westcoast da_westtamar
    ]
    known.each do |t|
      assert_equal t, DB.validate_table_name!(t), "Expected #{t} to be valid"
    end
  end

  # --- Invalid names ---

  def test_no_da_prefix_raises
    assert_raises(ArgumentError) { DB.validate_table_name!("users") }
  end

  def test_sql_injection_raises
    assert_raises(ArgumentError) { DB.validate_table_name!("da_foo; DROP TABLE users--") }
  end

  def test_backtick_injection_raises
    assert_raises(ArgumentError) { DB.validate_table_name!("da_foo`") }
  end

  def test_empty_string_raises
    assert_raises(ArgumentError) { DB.validate_table_name!("") }
  end

  def test_nil_raises
    assert_raises(ArgumentError) { DB.validate_table_name!(nil) }
  end

  def test_uppercase_raises
    # Table names are lowercase by convention; uppercase would be unexpected
    assert_raises(ArgumentError) { DB.validate_table_name!("DA_BRIGHTON") }
  end

  def test_whitespace_raises
    assert_raises(ArgumentError) { DB.validate_table_name!("da_foo bar") }
  end

  def test_error_message_includes_name
    err = assert_raises(ArgumentError) { DB.validate_table_name!("bad_name") }
    assert_includes err.message, "bad_name"
  end
end
