require 'user_agent_parser'

module Sessions
  class Metadata
    attr_accessor :ip_address, :location, :browser, :operating_system, :created_at, :updated_at, :expires_at, :deleted_at, :is_valid, :geo

    PARSER = UserAgentParser::Parser.new

    # rubocop:disable Metrics/ParameterLists
    def initialize(created_at: '', updated_at: '', expires_at: '', deleted_at: '', ip: '', location: '', user_agent: '', **_)
      # rubocop:enable Metrics/ParameterLists
      @ip_address = ip
      @created_at = created_at
      @updated_at = updated_at
      @expires_at = expires_at
      @deleted_at = deleted_at
      @location = location
      user_agent = user_agent

      parsed_agent = PARSER.parse(user_agent)

      @browser = parsed_agent.to_s
      @operating_system = parsed_agent.os.to_s

      @is_valid = begin
        if !deleted_at.nil? || !expires_at.nil? && expires_at.to_datetime.utc.past?
          false
        else
          true
        end
      end

      @geo = begin
                IpComparison.geo_lookup_ip(ip)
              rescue StandardError
                nil
              end
    end
  end
end
