module Sessions
  class Cookies < Sessions::Base
    CLIENT_ID = Settings.sessions.client_id

    def self.create(params)
      params = params.merge(client_id: CLIENT_ID.to_s)
      result = post '/sessions', body: params.to_json
      History::SessionAudit.new(admin_id: params[:creator_id], user_id: params[:user_id], ip_address: params[:ip]).add
      return result.body['token']
    end

    def self.delete_all(user_id)
      body = JSON.dump(client_id: CLIENT_ID)
      response = post "/sessions/#{user_id}/invalidate", body: body
      response.success?
    end

    def self.list(user_id)
      body = JSON.dump(client_id: CLIENT_ID)
      response = post "/sessions/#{user_id}", body: body

      if response.success?
        sessions = response.body['sessions']
        return sessions.map {|session| Sessions::Metadata.new(**session.except('metadata').symbolize_keys, **session['metadata'].symbolize_keys)}
      else
        return from_errors(response.body["msg"]) unless response.success?
      end
    end
  end
end
