# typed: strict
class GlobalState < ReduxApplicationRecord
  validates :key, presence: true, uniqueness: true
  validates :value, presence: true
  validates :value_type, presence: true

  enum :value_type,
       { string: 0, counter: 1, duration: 2, password: 3 },
       prefix: :value_type

  validate :validate_value_format

  sig { params(key: String).returns(T.nilable(String)) }
  def self.get(key)
    find_by(key: key)&.value
  end

  sig { params(key: String, value: String).returns(String) }
  def self.set(key, value)
    record = find_or_initialize_by(key: key)
    record.value = value
    record.save!
    value
  end

  sig { returns(T.nilable(String)) }
  def display_value
    case value_type&.to_sym
    when :password
      "••••••••"
    else
      value
    end
  end

  private

  sig { void }
  def validate_value_format
    value_type = self.value_type || return
    value = self.value || return

    case value_type.to_sym
    when :counter
      unless value.match?(/\A-?\d+\z/)
        errors.add(:value, "must be a valid integer for counter type")
      end
    when :duration
      unless value.match?(/\A\d+[smhd]\z/)
        errors.add(
          :value,
          "must be a valid duration (e.g., '30s', '5m', '2h', '1d')",
        )
      end
    end
  end
end
